在我的 UIViewController A
中,我有一些容器 View ,它加载了一些其他的 UIViewController B
。
我希望 UIViewController A
能够知道在它自己的容器中发生了什么。
问题是,我无法从容器访问其中的 View 。
例如,容器有一个带有 textfield
的 View Controller ,我想让 viewA 知道有人开始打字的时间。
我必须使用委托(delegate)
,或者有一种方法可以从容器 View 中获取数据?
最佳答案
一个 child UIViewController can access it's parent with
ParentViewController` 并使用它向父级发送消息。您可以直接执行此操作,但是...
根据交互级别,最好创建一个父接口(interface) UIViewController
实现。当 child UIViewController
添加到父级时,它会获取对实现该接口(interface)的对象的引用。它提供了对象之间强大的交互,同时也保持了适当的封装,这就是委托(delegate)模式。
所以我的答案是,您不必使用委托(delegate)模式,但这似乎是一个合适的解决方案。如果您不使用委托(delegate)模式,您可能会发现自己有一对耦合度如此之高的对象,您还不如将其设为一个对象。
// Somewhere in your view controller A you want to add B as a child
B *b = [[B alloc] init]; // create view controller B
b.delegate = self; // set up A as the delegate to B
// Add B as child
[self addChildViewController:b];
[self.containerView addSubview:b.view];
当 B
作为 child 添加到 A
代表已设置。假设A
实现一个接口(interface),B
将具有类似 @property (weak, nonatomic) id<MySomethingDelegate> delegate;
的属性B
应该能够在任何时候调用任何委托(delegate)方法。
关于ios - 从容器 View 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21879246/