addChildViewController手动控制UIView
平时使用 [self.view addSubview:<#(nonnull UIView *)#>]过多 今天首次尝试 addChildViewController 即直接添加子视图控制器
涉及三个VC ParentViewController、OrangeViewController、PurpleViewController
话不多说 直接上代码
主要是 ParentViewController代码
-
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor=[UIColor grayColor];
// 初始化控制器
[self controllersInit];// 初始化要展示的区域
[self showViewInit];// 初始化按钮
[self buttonConfig];
}
pragma mark - 初始化控制器
- (void)controllersInit
{
// 初始化两个控制器并作为root控制器的subController
_orangeVC = [OrangeViewController new];
[self addChildViewController:_orangeVC];
[_orangeVC didMoveToParentViewController:self];
_purpleVC = [PurpleViewController new];
[self addChildViewController:_purpleVC];
[_purpleVC didMoveToParentViewController:self];
[_purpleVC.view setFrame:self.view.bounds];
}
pragma mark - 初始化要展示的区域
-
(void)showViewInit
{
// 初始化要展示的区域
self.showView = [UIView new];
self.showView.frame = CGRectMake(0, 0, SCR_WIDTH, SCR_HEIGHT - downHeight - 10);
self.showView.layer.masksToBounds = YES;
[self.view addSubview:_showView];// 将第一个控制器的view添加进来展示
[self.showView addSubview:_orangeVC.view];showVC = _orangeVC;
}
pragma mark - 初始化按钮以及按钮事件
-
(void)buttonConfig
{
UIButton *firstVCButton = [UIButton new];
[self.view addSubview:firstVCButton];
firstVCButton.backgroundColor = [UIColor purpleColor];
firstVCButton.tag = 1000;
firstVCButton.frame = CGRectMake(0, SCR_HEIGHT - downHeight, SCR_WIDTH / 2, downHeight);
[firstVCButton addTarget:self
action:@selector(buttonsEvent:)
forControlEvents:UIControlEventTouchUpInside];UIButton *secondVCButton = [UIButton new];
[self.view addSubview:secondVCButton];
secondVCButton.backgroundColor = [UIColor orangeColor];
secondVCButton.tag = 2000;
secondVCButton.frame = CGRectMake(SCR_WIDTH / 2, SCR_HEIGHT - downHeight, SCR_WIDTH / 2, downHeight);
[secondVCButton addTarget:self
action:@selector(buttonsEvent:)
forControlEvents:UIControlEventTouchUpInside];
} -
(void)buttonsEvent:(UIButton *)button
{
if (button.tag == 1000)
{
if (showVC == _orangeVC)
{
return;
}[self transitionFromViewController:showVC toViewController:_orangeVC duration:0.5 options:UIViewAnimationOptionTransitionNone animations:^{ } completion:^(BOOL finished) { showVC = _orangeVC; }];
}
if (button.tag == 2000)
{
if (showVC == _purpleVC)
{
return;
}[self transitionFromViewController:showVC toViewController:_purpleVC duration:0.5 options:UIViewAnimationOptionTransitionNone animations:^{ } completion:^(BOOL finished) { showVC = _purpleVC; }];
}
}
OrangeViewController、PurpleViewController 仅仅设置了背景色 多多担待