我想在 VC 关闭时将我的数据从一个 ViewController
传递到另一个 VC。可能吗?
我已经尝试了下一个方法但没有成功:
点击按钮:
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
。
如何在关闭时将数据从 my ViewController
传递到 EditViewController
?
最佳答案
将数据传回前一个 View Controller 的最佳方法是通过委托(delegate)...从 ViewController A 到 B 时,将 View Controller A 作为委托(delegate)传递,并在 ViewController B 的 viewWillDisappear 方法上调用委托(delegate)方法ViewController A.. 协议(protocol)将有助于定义委托(delegate)和由以前的 VC 实现的所需方法。这是一个简单的例子:
传递数据的协议(protocol):
protocol isAbleToReceiveData {
func pass(data: String) //data: string is an example parameter
}
View Controller 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)
}
}
关闭 View Controller :
class viewControllerB: UIViewController {
var delegate: isAbleToReceiveData
viewWillDisappear {
delegate.pass(data: "someData") //call the func in the previous vc
}
}
关于ios - 如何在关闭 ViewController 时将数据传递给另一个 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706662/