我有两个视图,ParentViewController和ChildViewController;我想在ParentViewController中嵌套ChildViewController。我在故事板中设计了ParentViewController和ChildViewController。ParentViewController.m包含父对象的逻辑,ChildViewController.m包含子对象的逻辑。在ParentViewController.m中,我像这样添加子对象:
ChildViewController *childVC = [self.storyboard instantiateViewControllerWithIdentifier:@"ChildSBI"];
[self addChildViewController:childVC];我的问题是:如何将信息(如NSString)从子进程接收回父进程?我应该通过delegation完成此操作吗
发布于 2014-06-10 03:11:15
一种常见的模式是将child作为parent的属性,并将parent作为child的委托。你需要做的第一件事就是制定你自己的协议。
// MyProtocol.h
- (void)heyParentSomethingHappened:(Something)something;接下来,将child设置为parent的属性,以便它们可以通过委托进行通信。
// ParentVC.m
@interface ParentVC()
@property (nonatomic) ChildVC *child
@end既然parent已经将child作为一个属性,那么他们就需要用某种方式来交流。这就是委派的用武之地。使父级符合MyProtocol。
// ParentVC.h
@interface ParentVC : UIViewController <MyProtocol>既然parent符合您的特殊协议,就让child将其作为委托。
//ChildVC.h
@interface ChildVC : UIViewController
@property (nonatomic) id <MyProtocol> delegate.
@end现在child有了delegate属性,将其设置为parent就可以了。
// ParentVC.m
- (id)init {
// do your init
self.child.delegate = self // both (child.delegate, self) conform to <MyProtocol>, so no type mismatch.
}现在,当你的child需要提醒你的parent一些事情时,他们有一个正式的方式通过协议+委托进行交谈。
// ChildVC.m
- (void)someFunc {
[self.delegate heyParentSomethingHappend:[Something new]];
}请记住,在使用协议文件时,一定要将其包括在内。
https://stackoverflow.com/questions/24127057
复制相似问题