swift 按下ViewController可以通过按钮工作,但不能通过委托工作

kq0g1dla  于 2023-06-21  发布在  Swift
关注(0)|答案(1)|浏览(92)

故事板看起来像这样NavigationController -> HomeScreenVC -> LogInVC(模态)当我的登录成功时,我想关闭LogInVC并推送MyAccountVC我做了一个委托,当LogInVC被关闭时宣布HomeScreenVC,但我的推送不起作用,我会让下面的代码:

func logInSucceded() {
    print("delegate123")
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let viewController = storyboard.instantiateViewController(withIdentifier: "MyAccountViewController") as! MyAccountViewController
    navigationController?.pushViewController(viewController, animated: true)
}

@IBAction func loginbutton(_ sender: Any) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let viewController = storyboard.instantiateViewController(withIdentifier: "MyAccountViewController") as! MyAccountViewController
    navigationController?.pushViewController(viewController, animated: true)
}

我试着做一个直接的uibutton(在HomeScreenVC中)作为测试,如果我正确地编写了我的push,并且从按钮它可以工作,但是logInSucceded()不能。打印出现在控制台,所以我猜委托设置正确。有什么想法吗?谢谢!

m4pnthwp

m4pnthwp1#

在LogInVC中创建委托协议

protocol LogInDelegate: AnyObject {
    func logInSucceeded()
}

在LogInVC中,声明弱委托属性

weak var delegate: LogInDelegate?

登录成功后,调用delegate方法并关闭LogInVC

func logInSucceeded() {
    delegate?.logInSucceeded()
    dismiss(animated: true, completion: nil)
}

在HomeScreenVC中,遵循LogInDelegate协议,实现delegate方法

extension HomeScreenVC: LogInDelegate {
    func logInSucceeded() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "MyAccountViewController") as! MyAccountViewController
        navigationController?.pushViewController(viewController, animated: true)
    }
}

最后,在HomeScreenVC中,当呈现LogInVC时,将HomeScreenVC设置为delegate:

@IBAction func loginButton(_ sender: Any) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let loginVC = storyboard.instantiateViewController(withIdentifier: "LogInViewController") as! LogInViewController
    loginVC.delegate = self
    present(loginVC, animated: true, completion: nil)
}

使用这种方法,当登录在LogInVC中成功时,它将调用delegate方法,该方法反过来将解除LogInVC并从HomeScreenVC推送MyAccountVC。

相关问题