就像Schemtrical所说,使用委托是访问MainViewController中的方法的一种简单方法。
既然您将其标记为 Swift,我还将为您提供一个 Swift 中委托的小示例。
首先创建一个协议:
protocol NameOfDelegate: class { // ":class" isn't mandatory, but it is when you want to set the delegate property to weak
func someFunction() -> String // this function has to be implemented in your MainViewController so it can access the properties and other methods in there
}
在你的 MainViewController 中你必须添加:
class MainViewController: UIViewController, NameOfDelegate {
// your code
@IBAction func button(sender: UIButton) {
performSegueWithIdentifier("toOtherViewSegue", sender: self)
}
fun someFunction() -> String {
// access the other methods and return it
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toOtherViewSegue" {
let destination = segue.destinationViewController as! OtherViewController
destination.delegate = self
}
}
}
最后一步,您必须添加委托的属性,以便您可以与其“交谈”。就我个人而言,我认为这个属性是两个视图控制器之间的某种门,以便它们可以相互通信。
class OtherViewController: UIViewController {
weak var delegate: NameOfDelegate?
@IBAction func button(sender: UIButton) {
if delegate != nil {
let someString = delegate.someFunction()
}
}
}
我假设您使用了 segue 来访问其他 ViewController,因为您在帖子中提到了它。这样,您就可以与 MainViewController “对话”。
EDIT:
至于放松。这也可以通过 segue 来完成。
- add:
@IBAction func unwindToConfigMenu(sender: UIStoryboardSegue) { }
到你的MainViewController。
- 在故事板的顶部有 3 个图标
OtherViewController
。单击内部有正方形的黄色圆形,以确保选择了 ViewController 而不是内部的某些元素。
- 控制拖动(或鼠标右键拖动)从同一个内部有正方形的黄色圆形图标到最右边的红色正方形图标。这样做会弹出一个菜单,您可以在其中选择展开转场。
- 单击您刚刚创建的新 Segue。给它一个标识符,如“backToMain”
- 添加类似于下面代码的内容
OtherViewController
看来我不能再发布任何代码了? :o 稍后添加。