我是 xcode 7 的新手,如果你能帮我做点什么就太好了。
我有两个 ViewController,我想从 ViewController1 调用 ViewController2。我需要通过代码来做到这一点。 (我想从 viewDidLoad() 函数中调用它)
提前致谢
最佳答案
根据您的项目和导航设置,这是实现我认为您所要求的众多方法之一。
如果您使用 Segues 进行导航,在 ViewController1(初始化导航)中,您将覆盖 prepareForSegue 函数,将您的 segue.destination 转换为 ViewController2 并设置该属性。像这样
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard let viewController2 = segue.destination as? ViewController2 else { return }
viewController2.propertyName = "Property Value"
}
或者,如果您想在 ViewController1
中实例化 ViewController2
,您可以这样做:
override viewDidLoad() {
super.viewDidLoad()
guard let viewController2 = self.storyboard?.instantiateViewController(withIdentifier: "ID for ViewController (set in the Storyboard)") as? ViewController2 else { return }
viewController2.propertyName = "Property Value"
self.present(viewController2, animated: true, completion: nil)
// Or you could do if you want a full navigation, not just a modal.
self.show(viewController2, sender: self)
}
如果你想访问每个 View Controller ,你可以这样做:
class ViewController2: UIViewController {
weak var viewController1: ViewController1? //The 'weak' keyword is incredibly important so that you don't have a memory leak.
override viewDidLoad() {
self.viewController1.propertyName = "Property Value"
}
}
使用与上述相同的步骤,您可以在 ViewController2
实例中设置 viewController1
属性。
现在我希望这能回答您的问题。你的问题有点含糊,所以我在黑暗中拍摄。
关于ios - 如何在 xcode 7 中通过代码调用不同的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45151116/