父子控制器

父子控制器

自定义类似一个 UITabBarController的控制器能切换viewController

  • 首先,如果2个控制器的view是父子关系,那么2个控制器之间要成为父子关系,不然容易出现许多问题,比如作为子类的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;

添加一个子控制器

//a成为了self的子控制器
//self成为了a的父控制器
[self addChildViewController:a];
// 通过addChildViewController添加的控制器都会存在于childViewControllers数组中

获得父控制器

@property(nonatomic,readonly) UIViewController *parentViewController;

将一个控制器从它的父控制器中移除

// 控制器a从它的父控制器中移除
[a removeFromParentViewController];

实例演示1

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIView *contentView;

@property(nonatomic,strong)NSArray * colorViews;

@property(nonatomic,strong)UIView *curView;

@end

@implementation ViewController


- (void)viewDidLoad {



    [super viewDidLoad];

    RedViewController *red=[[RedViewController alloc]init];

    YellowViewController *yellow=[[YellowViewController alloc]init];

    BlueViewController  *blue=[[BlueViewController alloc]init];

    self.colorViews=@[red, yellow, blue];

    for (UIViewController * one in  self.colorViews)
    {
        [self addChildViewController:one];

    }


}

- (IBAction)btnClick:(UIButton *)sender
{


    [self.curView removeFromSuperview];
   //获取当前按钮所在父类按钮控件所列objc的顺序
    NSInteger index =[sender.superview.subviews  indexOfObject:sender];

    self.curView=((UIViewController *) (self.colorViews[index])).view;

    self.curView.frame=self.contentView.bounds;

    [self.contentView addSubview:self.curView];

}

@end
  • 点击按钮就能切换red,yellow,blue等控制器并显示view了
posted @ 2016-06-19 22:17  oblivious  阅读(252)  评论(0)    收藏  举报