在我的UIViewController A
我有一些容器视图,它会加载其他UIViewController B
。
我希望UIViewController A
能够知道自己的容器中发生了什么。
问题是,我无法从容器访问其中的视图。
例如,容器有一个带textfield
的视图控制器,我想让viewA知道有人何时开始输入。
我必须使用delegates
,或者有办法从容器视图中获取数据吗?
答案 0 :(得分:1)
子UIViewController can access it's parent with
parentViewController`并使用它向父母发送消息。你可以直接这样做,但是......
根据交互级别,最好创建父UIViewController
实现的接口。当子UIViewController
被添加到父项时,它将获得对实现该接口的对象的引用。它提供了对象之间的强大交互,但也保持了适当的封装,它是委托模式。
所以我的答案是,你不必使用委托模式,但它似乎是一个合适的解决方案。如果你不使用委托模式,你可能会发现自己有一对如此重叠的对象,你可能只是把它作为一个对象。
// 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
作为子项添加到A
时,委托会被设置。假设A
实现了一个界面,B
将拥有像@property (weak, nonatomic) id<MySomethingDelegate> delegate;
B
这样的属性应该能够在任何时候调用任何委托方法。