我需要通过popView将一些数据从secondView发送回First View。 我如何通过popViewControllerAnimated发回数据?
谢谢!
答案 0 :(得分:68)
您可以使用delegate
protocol
ChildViewController
delegate
ChildViewController
变量
ChildViewController
MainViewController
协议
ChildViewController
MainViewController
的{{1}}
navigate
delegate
方法
MainViewController
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
,则此解决方案将失效。因此,请明智地使用。