如何使用视图控制器传回信息

How to pass information back with view controllers

我有一个视图控制器和一个 table 视图控制器。我从 VC 一桌转到 VC 桌。在 VC 表上,我 select 一个(单元格)数据来自我存储在值中的字符串类型。当我按下一个单元格时,我想将该数据发送回 VC One。 并显示在按钮或标签中。

如何使用情节提要来做到这一点?

你应该看看协议 / 授权:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

第一个解决方案:使用回调

在您的 VCOne 中:

@IBAction func goToViewController2(sender: AnyObject) {
        let vc2 = storyboard?.instantiateViewControllerWithIdentifier("ViewController2") as! ViewController2
        vc2.callback = ({ string in
            self.myString = string
        })
        presentViewController(vc2, animated: true, completion: nil)
    }

在您的 VCTable 中:

创建回调变量:

var callback: ((String) -> Void)?

在您的 didSelectRowAtIndexPath 方法中,通过以下方式将其发送到 VCOne:

callback?(textField.text!)

第二种解决方案:使用引用

@IBAction func goToViewController2(sender: AnyObject) {
        let vc2 = storyboard?.instantiateViewControllerWithIdentifier("ViewController2") as! ViewController2
        vc2.vc1 = self
        presentViewController(vc2, animated: true, completion: nil)
    }

在您的 VCTable 中:

创建这个变量:

var vc1: ViewController?

在您的 didSelectRowAtIndexPath 方法中,通过以下方式将其发送到 VCOne:

vc1?.myString = textField.text!

第三种解决方案:使用 Delegate 看到 link 正如@Andre Slotta 所说。

第四个解决方案:使用 CenterNotification 谷歌搜索 :).

希望对您有所帮助:)