如何通过popViewControllerAnimated为Swift发回数据?

时间:2015-06-03 10:59:11

标签: ios swift

我需要通过popView将一些数据从secondView发送回First View。 我如何通过popViewControllerAnimated发回数据?

谢谢!

4 个答案:

答案 0 :(得分:68)

您可以使用delegate

传回数据
  1. protocol
  2. 中创建ChildViewController
  3. delegate
  4. 中创建ChildViewController变量
  5. ChildViewController
  6. 中扩展MainViewController协议
  7. ChildViewController
  8. 时提及MainViewController的{​​{1}}
  9. navigate
  10. 中定义delegate方法
  11. 然后,您可以从MainViewController
  12. 调用delegate方法

    示例

    在ChildViewController中:在下面编写代码......

    ChildViewController

    在MainViewController中

    protocol ChildViewControllerDelegate
    {
         func childViewControllerResponse(parameter)
    }
    
    class ChildViewController:UIViewController
    {
        var delegate: ChildViewControllerDelegate?
        ....
    }
    

    有两种选择:

    A)与Segue

    // extend `delegate`
    class MainViewController:UIViewController,ChildViewControllerDelegate
    {
        // Define Delegate Method
        func childViewControllerResponse(parameter)
        {
           .... // self.parameter = parameter
        }
    }
    

    B)没有Segue

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
    {
       let goNext = segue.destinationViewController as ChildViewController
       goNext.delegate = self
    }
    

    方法调用

    let goNext = storyboard?.instantiateViewControllerWithIdentifier("childView") as ChildViewController
    goNext.delegate = self
    self.navigationController?.pushViewController(goNext, animated: true)
    

答案 1 :(得分:16)

如果你想通过弹出发送数据,你可以这样做:

func goToFirstViewController() {
  let a = self.navigationController.viewControllers[0] as A
  a.data = "data"
  self.navigationController.popToRootViewControllerAnimated(true)
}

答案 2 :(得分:0)

此处给出的答案有点复杂,只需使用UINavigationControllerDelegate

class FirstNavigationController: UIViewController {
    var value: String?
}

class SecondNavigationController: UIViewController, UINavigationControllerDelegate {

    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        guard let vc = navigationController.topViewController as? FirstNavigationController else { return }
        vc.value = "Hello again"
    }
}

答案 3 :(得分:0)

在您的ViewController不是堆栈中的第一个VC的情况下扩展Dheeraj的答案,这是解决方案:

func popViewController() {
  guard let myVC = self.navigationController?.viewControllers.first({ $0 is MyViewController })
  myVC.data = "data"
  self.navigationController?.popViewController(animated: true)
}

但是,如果堆栈中有2个或多于2个MyViewController,则此解决方案将失效。因此,请明智地使用。