我一直在寻找一个答案,但只找到了答案.
我有一个viewController1与一个按钮到viewController2.没有代码,我通过界面构建器设置.在viewController2上,我有一个关闭自己的按钮
self.dismissViewControllerAnimated(true,completion,nil)
当视图被关闭时,我想将一个字符串从viewController2传回给ViewController1.我该怎么做呢?此外,我正在使用swift.
提前致谢!
有两种常见的模式,这两种都不需要viewController2明确地知道viewController1(这对于可维护性是非常好的):
>为viewController2创建一个委托协议,并将viewController1设置为委托.无论何时要将数据发送回viewController1,都要让viewController2发送“委托”数据
>将一个闭包设置为允许传递数据的属性. viewController1会在显示viewController2时在viewController2上实现该关闭.每当viewController2具有要传回的数据时,它将调用闭包.我觉得这种方法比较“快”.
以下是#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) } } } } }