天天看点

使用addChildViewController手动控制UIViewController的切换

使用addChildViewController手动控制UIViewController的切换

addchildviewcontroller

if the new child view controller is already the child of a container view controller, it is removed from that container before being added.

this method is only intended to be called by an implementation of a custom container view controller. if you override this method, you must call super in your implementation.

如果这个子 view controller 已经被添加到了一个容器 controller 当中,那在它被添加进新的容器controller之前会从旧的容器中移除.

这个方法只能被用来实现一个自定义的容器controller添加子controller.如果你重写了这个方法,你必须调用super方法.

使用源码:

使用addChildViewController手动控制UIViewController的切换

appdelegate.h + appdelegate.m

rootviewcontroller.h + rootviewcontroller.m

firstviewcontroller.h + firstviewcontroller.m

secondviewcontroller.h + secondviewcontroller.m

使用addChildViewController手动控制UIViewController的切换
使用addChildViewController手动控制UIViewController的切换

需要注意的地方:

1. 容器controller最好定义一个专门用来展示子controller相关view的区域,如例子中的,其中,maskstobounds很重要,要不然,整个controller都会被展示出来的.

    self.showarea = [uiview new];

    self.showarea.frame = cgrectmake(0, 0, 320, scr_height - downlenth - 10);

    self.showarea.layer.maskstobounds = yes;

    [self.view addsubview:_showarea];

    [self.showarea addsubview:_firstvc.view];

2. 调用完addchildviewcontroller之后还需要调用didmovetoparentviewcontroller,官方文档里面有说明.

3. 为什么在点击一个按钮切换控制器的时候,showarea什么都不用设置,为何还能显示出变化呢?

    其实这一点我也没弄明白为何呢.

4. 这个与uitabbarcontroller的功能类似,都有懒加载功能,实际上可以用来当做模拟uitabbarcontroller使用,具备更高自由度的定制tabbar的功能.

继续阅读