iOS addChildController的方法

iOS addChildController的方法,第1张

使用默认的ViewController作为盛放childController 的容器。创建FirstViewController作为ChildViewController。在这里我只是简单的实验了一下两个控制器之间的跳转,其中并没有加入数据。因为两个控制器是分离开的。所以很大程度上降低了耦合度。

1 在viewcontroller中

@property(nonatomic, strong) UIViewController *currentVC记录当前的控制器 将viewcontroller 作为当前的控制器 _currentVC = self

2 创建点击按钮,点击d出childViewController 

[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside]

3 将firstViewController声明为全局变量。以便后续 *** 作。

4 点击viewcontroller中的按钮 响应事件如下

- (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(@"完成")

}]

}

********重要的点在点击按钮时 ,按钮响应方法中 [self addChildViewController:_firstVC]

和[self.view addSubview:_firstVC.view]一个是讲firstVC作为当前控制器的子视图控制器。另一个addSubview方法是讲firstVC的视图添加到当前视图,作为子视图显示。在firstVC视图出现时,我添加了动画效果。

5 在firstViewControl中 需要有回调方法。在这里我用的block 在firstViewController中我添加了一个点击按钮。点击按钮会将Block传到viewController中

- (void)btnClick:(UIButton *)btn {

self.firstBlock()

}

6 在viewcontroller中 接受childViewcontroller传过来的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(@"完成")

}]

}

在这里由于用到动画,所以涉及到firstViewController中的frame。在这里就会牵扯到block的循环引用问题了。 __weak FirstViewController *weakSelf = firstVC用__weak修饰自身。weak是弱引用,不会持有对象。所以在block里面使用self时就不会再造成相互持有。retain cycle了。[weakSelf removeFromParentViewController]firstVC 从当前视图控制器中移除。在动画完成时 将当前的currentVC = self

比如说有两个控制器,一个是FirstViewController,一个是SecondViewController,如果要在FirstViewController上添加SecondViewController,则在FirstViewController中,

SecondViewController *secondVc = [[SecondViewController alloc] init]

[self addChildViewController:secondVc]

这就把一个控制器添加到另一个控制器上去了

但是仅仅如此还是不够 严谨的,苹果官方建议,当一个控制器成为另一个控制器的子控制器时,其对应的view也要成为另一个控制器的子View.

即,添加完控制器之后,在加一句

[self.view addSubView:secondVc.view]


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/bake/8029654.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-12
下一篇2023-04-12

发表评论

登录后才能评论

评论列表(0条)

    保存