首页 > 解决方案 > 如何 popViewController 并发送回数据

问题描述

我有以下代码可以返回最后一个视图控制器

  self.navigationController?.popViewController(animated: true)

当我这样做时,如何将数据发送回最后一个视图控制器?

标签: iosswift

解决方案


Swift 很大程度上依赖于委托模式,这是一个使用它的好地方。

class FirstViewController: UIViewController {
    func pushToSecondViewController() {
        let second = SecondViewController()
        second.firstViewControllerDelegate = self // set value of delegate
        navigationController?.pushViewController(second, animated: true)
    }
    
    func someDelegateMethod() {
        print("great success")
    }
}

class SecondViewController: UIViewController {
    weak var firstViewControllerDelegate: FirstViewController? // establish a delegate
    
    func goBackToFirstViewController() {
        firstViewControllerDelegate?.someDelegateMethod() // call delegate before popping
        navigationController?.popViewController(animated: true)
    }
}

推荐阅读