问题描述
我想在 VC 关闭时将我的数据从一个 ViewController
传递到另一个 VC.可能吗?
I want to pass my data from one ViewController
to another VC on VC dismiss. Is it possible?
我尝试了下一个方法,但没有成功:
I've tried the next method and no success:
点击按钮:
self.dismiss(animated: true) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "EditViewController") as! EditViewController
controller.segueArray = [values]
}
当 EditViewController
再次出现时,我的 segueArray
是 nil
.
when EditViewController
appears again, my segueArray
is nil
there.
如何在解除时将数据从 my ViewController
传递到 EditViewController
?
How can I pass my data from my ViewController
to the EditViewController
on dismiss?
推荐答案
将数据传回上一个视图控制器的最佳方式是通过委托...当从 ViewController A 到 B 时,将视图控制器 A 作为委托传递在 ViewController B 的 viewWillDisappear 方法上,调用 ViewController A 中的委托方法.这是一个简单的例子:
The best way to pass data back to the previous view controller is through delegates... when going from ViewController A to B, pass view controller A as a delegate and on the viewWillDisappear method for ViewController B, call the delegate method in ViewController A.. Protocols would help define the delegate and the required methods to be implemented by previous VC. Here's a quick example:
传递数据的协议:
protocol isAbleToReceiveData {
func pass(data: String) //data: string is an example parameter
}
视图控制器 A:
class viewControllerA: UIViewController, isAbleToReceiveData {
func pass(data: String) { //conforms to protocol
// implement your own implementation
}
prepare(for: Segue) {
/** code for passing data **/
let vc2 = ViewCOntrollerB() /
vc2.delegate = self //sets the delegate in the new viewcontroller
//before displaying
present(vc2)
}
}
关闭视图控制器:
class viewControllerB: UIViewController {
var delegate: isAbleToReceiveData
viewWillDisappear {
delegate.pass(data: "someData") //call the func in the previous vc
}
}
这篇关于如何在关闭 ViewController 时将数据传递给另一个控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!