平時使用 [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];// 初始化要展示的區(qū)域
[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 - 初始化要展示的區(qū)域
-
(void)showViewInit
{
// 初始化要展示的區(qū)域
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添加進(jìn)來展示
[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 僅僅設(shè)置了背景色 多多擔(dān)待