使用默認(rèn)的ViewController作為盛放childController 的容器。創(chuàng)建FirstViewController作為ChildViewController。在這里我只是簡(jiǎn)單的實(shí)驗(yàn)了一下兩個(gè)控制器之間的跳轉(zhuǎn),其中并沒(méi)有加入數(shù)據(jù)。因?yàn)閮蓚€(gè)控制器是分離開(kāi)的。所以很大程度上降低了耦合度。
1 在viewcontroller中
@property(nonatomic, strong) UIViewController *currentVC; 記錄當(dāng)前的控制器 將viewcontroller 作為當(dāng)前的控制器 _currentVC = self;
2 創(chuàng)建點(diǎn)擊按鈕,點(diǎn)擊彈出childViewController?
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
3 將firstViewController聲明為全局變量。以便后續(xù)操作。
4 點(diǎn)擊viewcontroller中的按鈕 響應(yīng)事件如下
- (void)btnClick:(UIButton *)btn {
[self addChildViewController:firstVC];
[self.view addSubview:firstVC.view];
[UIView animateWithDuration:2.0 delay:0.5 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
firstVC.baseView.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
} completion:^(BOOL finished) {
NSLog(@"完成");
}];
}
********重要的點(diǎn)在點(diǎn)擊按鈕時(shí) ,按鈕響應(yīng)方法中 [self addChildViewController:_firstVC];
和[self.view addSubview:_firstVC.view]; 一個(gè)是講firstVC作為當(dāng)前控制器的子視圖控制器。另一個(gè)addSubview方法是講firstVC的視圖添加到當(dāng)前視圖,作為子視圖顯示。在firstVC視圖出現(xiàn)時(shí),我添加了動(dòng)畫(huà)效果。
5 在firstViewControl中 需要有回調(diào)方法。在這里我用的block 在firstViewController中我添加了一個(gè)點(diǎn)擊按鈕。點(diǎn)擊按鈕會(huì)將Block傳到viewController中
- (void)btnClick:(UIButton *)btn {
self.firstBlock();
}
6 在viewcontroller中 接受childViewcontroller傳過(guò)來(lái)的block?
firstVC = [[FirstViewController alloc] init];
__weak FirstViewController *weakSelf = firstVC;
firstVC.firstBlock = ^(){
[weakSelf removeFromParentViewController];
[UIView animateWithDuration:2.0 delay:0.5 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
weakSelf.baseView.frame = CGRectMake(0, -weakSelf.baseView.frame.size.height, weakSelf.baseView.frame.size.width, weakSelf.baseView.frame.size.height);
} completion:^(BOOL finished) {
[weakSelf.view removeFromSuperview];
_currentVC = weakSelf;
NSLog(@"完成");
}];
};
在這里由于用到動(dòng)畫(huà),所以涉及到firstViewController中的frame。在這里就會(huì)牽扯到block的循環(huán)引用問(wèn)題了。 __weak FirstViewController *weakSelf = firstVC; 用__weak修飾自身。weak是弱引用,不會(huì)持有對(duì)象。所以在block里面使用self時(shí)就不會(huì)再造成相互持有。retain cycle了。[weakSelf removeFromParentViewController]; firstVC 從當(dāng)前視圖控制器中移除。在動(dòng)畫(huà)完成時(shí) 將當(dāng)前的currentVC = self;