容器视图控制器:其实就是在一个viewController上面放两个或者多个viewcontroller,用父类viewcontroller切换子类控制器
新建一个viewController类,名字起为MovieListViewController
再建两个viewController作为子视图: ListViewController和CollectionViewController
在 MovieListViewController里引入另两个viewController的头文件并创建属性
#import "MovieListViewController.h"
#import "ListViewController.h"
#import "CollectionViewController.h"
@interface MovieListViewController ()
@property (nonatomic, assign)BOOL isSelected; //判断按钮当前的值
@property (nonatomic, retain)ListViewController *listVC;
@property (nonatomic, retain)CollectionViewController *collectionVC;
@end
@implementation MovieListViewController
//我是在MRC下,需要手动释放内存,ARC下不需要
- (void)dealloc
{
[_listVC release];
[_collectionVC release];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
//设置按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor = [UIColor yellowColor];
button.frame = CGRectMake(0, 0, 50, 30);
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"登陆" forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
//设置当前为NO
self.isSelected = NO;
self.listVC = [[ListViewController alloc] init];
//添加子视图控制器
//当前self作为容器视图控制器
[self addChildViewController:self.listVC];
[self.view addSubview:self.listVC.view];
[_listVC release];
self.collectionVC = [[CollectionViewController alloc] init];
[self addChildViewController:self.collectionVC];
[self.view addSubview:self.collectionVC.view];
[_collectionVC release];
}
//设置按钮点击事件
- (void)buttonAction:(UIButton *)btn{
if (self.isSelected == NO) {
//参数1:当前页面
//参数2:跳转到的页面
//参数3:持续时间
//参数4:跳转样式
[UIView transitionFromView:self.collectionVC.view toView:self.listVC.view duration:0.5 options:UIViewAnimationOptionTransitionFlipFromRight completion:^(BOOL finished) {
}];
}else{
[self.view bringSubviewToFront:self.collectionVC.view];
[UIView transitionFromView:self.listVC.view toView:self.collectionVC.view duration:0.5 options:UIViewAnimationOptionTransitionFlipFromLeft completion:^(BOOL finished) {
}];
}
//每点一次按钮isSelected的值就取反
self.isSelected = !self.isSelected;
}
在两个子视图viewController里设置不同背景颜色,点击按钮就可以看见效果了