我一直在寻找答案,但只能找到答案。
我的viewController1
带有一个按钮,可以锁定到viewController2
。没有代码,我通过“接口(interface)”构建器进行设置。在viewController2
上,我有一个按钮可以自行关闭
self.dismissViewControllerAnimated(true, completion, nil)
我想在 View 关闭时将字符串从
viewController2
传递回viewController1
。我该怎么做呢?另外,我正在使用swift。提前致谢!
最佳答案
有两种常见的模式,这两种模式都消除了viewController2明确了解viewController1的需要(这对于可维护性非常重要):
这是#2的一些示例代码:
class ViewController2 : UIViewController {
var onDataAvailable : ((data: String) -> ())?
func sendData(data: String) {
// Whenever you want to send data back to viewController1, check
// if the closure is implemented and then call it if it is
self.onDataAvailable?(data: data)
}
}
class ViewController1 : UIViewController {
func doSomethingWithData(data: String) {
// Do something with data
}
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
// When preparing for the segue, have viewController1 provide a closure for
// onDataAvailable
if let viewController = segue.destinationViewController as? ViewController2 {
viewController.onDataAvailable = {[weak self]
(data) in
if let weakSelf = self {
weakSelf.doSomethingWithData(data)
}
}
}
}
}
关于model-view-controller - 在Swift中传递数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24318480/