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

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

问题描述

假设我有一个自定义容器视图控制器(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.

推荐答案

您可以使用委托或阻止;

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天全站免登陆