【问题标题】:Passing data from modal segue to parent将数据从模态 segue 传递给父级
【发布时间】:2015-02-13 15:13:51
【问题描述】:

我想将数据(例如 set var)从模态 segue 传递给父级,我该怎么做?

我正在使用该代码退出模态转场:

@IBAction func doneClicked(sender: AnyObject) {
    self.dismissViewControllerAnimated(true, completion: nil)
}

我不能在这里使用 segue.destinationViewController 来传递数据,就像我过去在 push segues 上所做的那样。

【问题讨论】:

    标签: ios swift segue


    【解决方案1】:

    在模态视图控制器上创建协议

    protocol ModalViewControllerDelegate
    {
        func sendValue(var value : NSString)
    }
    

    同时在你的 Modal ViewController 类中声明

    var delegate:ModalViewControllerDelegate!
    

    在 ParentViewController 中包含这个协议 ModalViewControllerDelegate

    当你从一个视图控制器移动到另一个视图控制器时

     modalVC.delegate=self;
            self.presentViewController(modalVC, animated: true, completion: nil)
    

    您可以在 ParentViewcontroller 中获得您的价值

     func sendValue(value: NSString) {
    
        }
    

    终于在 ModalViewController 上

    @IBAction func doneClicked(sender: AnyObject) {
    delegate?.sendValue("value")
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    

    【讨论】:

    • 一个尼特,而不是“sendValue”,我会遵循苹果代表约定并使用类似modalView:finishedWithValue:sendValue的东西仍然将调用者和接收者捆绑在一起,而不是必要的。
    • 给你发什么链接?对于 Apple 遵循的委托约定,只需查看它们提供的任何模态视图控制器,例如 UIImagePickerController
    • 哦,我误解了我认为有更好的回调实现方法。你是对的 UIImagePickerController 例子是最好的。事实上,在 iOS 中我们使用了很多回调,它可能使用委托 NSNotifcations、block、Selctor。这种问题可以通过任何回调方法来解决。我喜欢使用委托、协议。我尽量避免使用 NSNotifications
    【解决方案2】:

    在第二个 viewController(segue 显示的那个)中声明一个变量,如

    var parentVC : UIViewController?
    

    那么当你从父级调用 segue 时

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
    {
        if segue.identifier == "yourSegue" {
            let secondController= segue.destinationViewController as UIViewController
    secondController.parentVC = self
        }
    }
    

    所以你可以使用

    @IBAction func doneClicked(sender: AnyObject) {
        self.parentVC.yourVariable = 0
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    

    【讨论】:

    • 真的不应该直接在其他视图控制器中胡闹,那样是疯狂的。如果你不对调用者做出假设,你也会获得很大的灵活性。遵循UIKit 设置的标准模型并在完成时使用委托和/或回调要好得多。见Shashi's answer
    猜你喜欢
    • 2021-11-14
    • 2019-03-07
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2011-09-07
    相关资源
    最近更新 更多