Ios 将数据从模式segue传递到父级

Ios 将数据从模式segue传递到父级,ios,swift,segue,Ios,Swift,Segue,我想将数据(如set var)从modal segue传递到父级,我该怎么做 我正在使用该代码退出modal segue: @IBAction func doneClicked(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } 我不能在这里使用segue.destinationViewController来传递数据,就像我在推式segue上所做的那样。在第二个viewCont

我想将数据(如set var)从modal segue传递到父级,我该怎么做

我正在使用该代码退出modal segue:

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

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

在第二个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)
}

在模态ViewController上创建协议

protocol ModalViewControllerDelegate
{
    func sendValue(var value : NSString)
}
@IBAction func doneClicked(sender: AnyObject) {
delegate?.sendValue("value")
    self.dismissViewControllerAnimated(true, completion: nil)
}
还可以在模态ViewController类中声明

var delegate:ModalViewControllerDelegate!
在ParentViewController中包括此协议ModalViewController Delegate

protocol ModalViewControllerDelegate
{
    func sendValue(var value : NSString)
}
@IBAction func doneClicked(sender: AnyObject) {
delegate?.sendValue("value")
    self.dismissViewControllerAnimated(true, completion: nil)
}
从一个viewController移动到另一个viewController时

 modalVC.delegate=self;
        self.presentViewController(modalVC, animated: true, completion: nil)
在这里,您可以在ParentViewcontroller中获得您的值

 func sendValue(value: NSString) {

    }
最后,关于ModalViewController

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

真的不应该直接在其他视图控制器中胡闹,那样的话就是疯狂。如果不对调用方进行假设,也可以获得很大的灵活性。更好的做法是遵循UIKit设置的标准模型,并在完成时使用委托和/或回调。请看。一个细节,而不是“sendValue”,我会遵循apple代理惯例,使用类似于
modalView:finishedWithValue:
sendValue
的东西,它仍然将呼叫者和接收者绑在一起,这是不必要的。向您发送指向什么的链接?对于Apple遵循的代理约定,只需看看它们提供的任何模态视图控制器,例如,
UIImagePickerController
。哦,我误解了,我认为有更好的方法实现回调。您是对的UIImagePickerController示例是最好的。事实上,在iOS中,我们使用了很多回调,可能是使用委托通知、块、选择器。任何回调方法都可以解决此类问题。我喜欢使用委托、协议。我尽量避免使用NSN通知