iOS邊練邊學--父子控制器之自定義控制器的切換


一、如圖所示的界面,按鈕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];

     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM