容器视图控制器 - 通知父操作 [英] Container View Controllers - notify parent of action

查看:17
本文介绍了容器视图控制器 - 通知父操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个自定义容器视图控制器 (MainViewController),我可以在其中执行以下操作:

Say I have a custom container view controller (MainViewController) where I do something like this:

- (void)viewDidLoad
{
    [super viewDidLoad];        

    HomeViewController *homeVC = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
    [self addChildViewController:homeVC];
    [self.view addSubview:homeVC.view];

}

HomeViewController 将有一个按钮,例如go",按下后需要前进到下一个视图控制器.所以我需要将此操作通知 MainViewController.这样做的最佳方法是什么?

The HomeViewController will have a button, such as "go", that when pressed will need to advance to the next view controller. So I need to notify the MainViewController of this action. What is the best way to do this?

我使用自定义容器是因为我需要在视图控制器之间进行自定义转换.当按下go"时,HomeViewController 上的一些视图将动画化,而新视图控制器中的视图动画化到位.

I'm using a custom container because I need to do custom transitions between the view controllers. When "go" is pressed, some of the views on the HomeViewController will animate while the views from the new view controller are animating into place.

显然我可以给 HomeViewController 一个 MainViewController 类型的属性并以这种方式进行调用,但我希望容器视图控制器 API 有一种更简洁的方式.

Obviously I could give the HomeViewController a property of type MainViewController and make calls that way, but I'm hoping that there is a cleaner way with the container view controller API.

推荐答案

可以使用delegate或者block;

You can either use delegate or block;

使用委托

创建协议:

@protocol SomeProtocol <NSObject>
- (void)someAction; 
@end 

只需像这样在 HomeViewController.h 中声明一个委托:

Just declare a delegate in HomeViewController.h like this:

id<SomeProtocol> delegate; 

然后在 MainViewController 的 viewDidLoad 中这样设置:

and then in MainViewController's viewDidLoad set it like this:

homeVC.delegate = self;
//some where in MainViewController implement the protocol method
-(void)someAction
{
    //do something
}

然后当你在 homeVC 中按下按钮时,只需调用:

then when you press the button in homeVC, just simply call:

if ([self.delegate respondsToSelector:@selector(someAction)]) {
    [self.delegate someAction];
}

使用屏蔽:

在 HomeViewController.h 中声明一个块属性:

In HomeViewController.h declare a block property:

typedef void (^ActionBlock)();

@property (nonatomic, copy) ActionBlock block;

然后在 MainViewController ViewDidLoad:

then in MainViewController ViewDidLoad:

homeVC.block = ^(){
    //do something
};

然后当你在 homeVC 中按下按钮时,只需调用:

then when you press the button in homeVC, just simply call:

self.block();

这篇关于容器视图控制器 - 通知父操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆