如何链接2个视图控制器? - 斯威夫特

时间:2015-04-24 12:22:46

标签: ios swift

我是Swift的新手,并尝试在之前的string中为数组添加viewController。在我的主视图控制器中,我有这个方法来声明viewController

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        var newSoundViewController = segue.destinationViewController as! NewSoundViewController
        newSoundViewController.previousViewController = self
}

NewSoundViewController中,我有一个方法可以将string添加到上一个viewController的数组中。这是代码:

@IBAction func saveTapped(sender: AnyObject) {
    var sound = Sound()
    sound.name = soundTextField.text
    self.previousViewController.sounds.append(sound)
    self.dismissViewControllerAnimated(true, completion: nil)
}

1 个答案:

答案 0 :(得分:2)

你可以做一些事情:

-Unwind segue(What are Unwind segues for and how do you use them?

-Delegate:您可以在那里创建@protocol并定义方法,声明委托(第二类),在第一堂课中面对协议,然后简单地调用self.delegate.thatMethod

为了完整起见,您可以使用更多内容:

-Singleton class

- 数据。

Unwind segue是您解决方案的最佳选择,因为您需要在两个彼此相邻的控制器之间进行通信。他们不需要彼此相邻,而是在同一个导航堆栈中(感谢@ABakerSmith)

当您需要在远程控制器之间进行通信时,委托是很好的。

Singleton通常用于配置,Core数据类似于数据库。最后两个不适合你的情况,所以我会使用unwind segue。

相关问题