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];
  • 相关阅读:
    Django笔记
    在vue框架里添加bootstrap与axios
    Mysql8和Mysql5.7部署同一服务器
    docker迁入迁出mysql
    mysql导出csv
    Yearning启停脚本(开机自启)
    go 语言的基础知识
    阅读《深入理解Kafka核心设计与实践原理》第五章 日志存储
    阅读《深入理解Kafka核心设计与实践原理》第四章 主题与分区
    阅读《深入理解Kafka核心设计与实践原理》第三章 消费者
  • 原文地址:https://www.cnblogs.com/AbeDay/p/5026903.html
Copyright © 2011-2022 走看看