一、如图所示的界面,按钮One、Two、Three分别对应三个控制器的view,点击实现切换。个人感觉父子控制器的重点在于,控制器的view们之间建立了父子关系,控制器不建立的话,发生在view上面的事件,对应的view可能接收不到,控制器们建立了父子关系后,可以将事件传递给相应的控制器。
练习代码如下
1 #import "ViewController.h"
2 #import "OneTableViewController.h"
3 #import "TwoViewController.h"
4 #import "ThreeViewController.h"
5
6 @interface ViewController ()
7 /** curView */
8 @property(nonatomic,strong) UIViewController *curVC;
9 /** old */
10 @property(nonatomic,assign) NSInteger oldIndex;
11 /** view */
12 @property(nonatomic,strong) UIView *contentView;
13 @end
14
15 @implementation ViewController
16
17 - (void)viewDidLoad {
18 [super viewDidLoad];
19
20 // 不给按钮,只给view做动画的解决办法 -- 多用一个view将要动画的view包起来,动画添加到这个view上
21 UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height - 64)];
22 [self.view addSubview:contentView];
23
24 self.contentView = contentView;
25
26 [self addChildViewController:[[OneTableViewController alloc] init]];
27 [self addChildViewController:[[TwoViewController alloc] init]];
28 [self addChildViewController:[[ThreeViewController alloc] init]];
29
30
31 }
32
33 - (IBAction)btnClick:(UIButton *)sender {
34
35 // 移除当前的
36 [self.curVC.view removeFromSuperview];
37
38 // 取出角标
39 NSInteger index = [sender.superview.subviews indexOfObject:sender];
40 // 根据角标从集合中取出相应的VC
41 self.curVC = self.childViewControllers[index];
42
43 self.curVC.view.frame = self.contentView.bounds;
44 [self.contentView addSubview:self.curVC.view];
45
46
47 CATransition *anim = [CATransition animation];
48 anim.type = @"cube";
49 anim.subtype = index > self.oldIndex ? kCATransitionFromRight : kCATransitionFromLeft;
50 anim.duration = 0.5;
51 [self.contentView.layer addAnimation:anim forKey:nil];
52 self.oldIndex = index;
53
54 }
55
56 @end
View Code
二、总结
- 如果两个控制的view是父子关系(不管是直接还是间接的父子关系),那么这两个控制器也应该为父子关系
[a.view addSubview:b.view];
[a addChildViewController:b];
// 或者
[a.view addSubview:otherView];
[otherView addSubbiew.b.view];
[a addChildViewController:b];
- 获得所有的子控制器
@property(nonatomic,readonly) NSArray *childViewControllers;
- 添加一个子控制器
//XMGOneViewController成为了self的子控制器
//self成为了XMGOneViewController的父控制器
[self addChildViewController:[[XMGOneViewController alloc] init]];
// 通过addChildViewController添加的控制器都会存在于childViewControllers数组中
- 获得父控制器
@property(nonatomic,readonly) UIViewController *parentViewController;
- 将一个控制器从它的父控制器中移除
// 控制器a从它的父控制器中移除
[a removeFromParentViewController];