我有一个弹出到 Storyboard中的容器 View 。有一个很棒的小箭头代表嵌入到另一个场景。该场景的顶级对象由自定义 UIViewController
控制。我想调用在我的自定义类中实现的方法。如果我有权访问容器,我如何获得对内部内容的引用?
最佳答案
您可以使用 prepareForSegue
(UIViewController
中的一种方法)从您当前的 View Controller 访问任何 UIViewController
,这包括 embed
segues。
来自关于prepareForSegue
的文档:
The default implementation of this method does nothing. Your view controller overrides this method when it needs to pass relevant data to the new view controller. The segue object describes the transition and includes references to both view controllers involved in the segue.
在您的问题中,您提到需要在您的自定义 View Controller 上调用一个方法。以下是您如何做到这一点的示例:
1. 为您的嵌入 segue 提供一个标识符。您可以在 Interface Builder 中执行此操作,方法是选择您的 segue,转到 Attributes Editor 并在Storyboard Embed Segue 下查看。
2. 创建类如下:
保留对 embeddedViewController
的引用,以便以后可以调用 myMethod
。它被声明为一个隐式展开的可选值,因为给它一个非零的初始值是没有意义的。
// This is your custom view controller contained in `MainViewController`.
class CustomViewController: UIViewController {
func myMethod() {}
}
class MainViewController: UIViewController {
private var embeddedViewController: CustomViewController!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? CustomViewController,
segue.identifier == "EmbedSegue" {
self.embeddedViewController = vc
}
}
// Now in other methods you can reference `embeddedViewController`.
// For example:
override func viewDidAppear(animated: Bool) {
self.embeddedViewController.myMethod()
}
}
3. 使用 Identity Inspector 在 IB 中设置您的 UIViewControllers
类。例如:
现在一切都应该正常了。希望对您有所帮助!
关于ios - 如何在 Swift 中获取容器内的 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29582200/