zoukankan      html  css  js  c++  java
  • IOS—通过ChildViewController实现view的切换

    IOS—通过ChildViewController实现view的切换

    在以前,一个UIViewController的View可能有很多小的子view。这些子view很多时候被盖在最后,我们在最外层ViewController的viewDidLoad方法中,用addSubview增加了大量的子view。这些子view大多数不会一直处于界面上,只是在某些情况下才会出现,例如登陆失败的提示view,上传附件成功的提示view,网络失败的提示view等。但是虽然这些view很少出现,但是我们却常常一直把它们放在内存中。另外,当收到内存警告时,我们只能自己手工把这些view从super view中去掉。

    我们现在可以使用下面的方法:

    addChildViewController: //添加

    removeFromParentViewController //删除

    transitionFromViewController:toViewController:duration:options:animations:completion://转换

    willMoveToParentViewController: //当一个视图控制器从视图控制器容器中被添加或者被删除之前,该方法被调用

    didMoveToParentViewController://当从一个视图控制容器中添加或者移除viewController后,该方法被调用。

    这样,就能够将一个页面中的UIViewController控制起来,而不是混乱的共用一个UIViewController

    ,最重要的是,编程习惯的革命:降低了功能的耦合度!

    下面是childViewController的一个简单使用例子

    //在parent view controller 中添加 child view controller
       FirstViewController *firstViewController=[[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];
        [self addChildViewController:firstViewController];
    
        SecondViewController *secondViewController=[[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
        [self addChildViewController:secondViewController];
    
        ThirdViewController *thirdViewController=[[ThirdViewController alloc] initWithNibName:@"ThirdViewController" bundle:nil];
        [self addChildViewController:thirdViewController];
    
        [self.view  addSubview:thirdViewController.view];
    
      // addChildViewController回调用[child willMoveToParentViewController:self] ,但是不会调用didMoveToParentViewController,所以需要显示调用
        [thirdViewController didMoveToParentViewController:self];
        currentViewController=thirdViewController;
    
      //切换child view controller
         [self transitionFromViewController:currentViewController toViewController:firstViewController duration:4 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
                }  completion:^(BOOL finished) {
                   //......
                }];
        currentViewController=firstViewController;
    
      //移除child view controller
        // removeFromParentViewController在移除child前不会调用[self willMoveToParentViewController:nil] ,所以需要显示调用
        [currentViewController willMoveToParentViewController:nil];
        [currentViewController removeFromSuperview];
        [currentViewController removeFromParentViewController];
  • 相关阅读:
    浅析什么是HOOK
    用diff命令生成Patch,用Patch命令打Patch
    Git 协作:Fetch Pull Push Branch Remote Rebase Cherry-pick相关
    apt-get update 101错误解决办法
    Python函数参数中的冒号与箭头
    Python中的多线程编程,线程安全与锁(二)
    使用pdb模块调试Python
    Python中的多线程编程,线程安全与锁(一)
    聊聊Python中的GIL
    Python中的单元测试模块Unittest快速入门
  • 原文地址:https://www.cnblogs.com/AbeDay/p/5026903.html
Copyright © 2011-2022 走看看