Swift:解决ViewController中viewWillAppear失效的问题

最近做了一个功能,大概是这样的,把 ViewController B、ViewController C...... 的view 添加到ViewController A中,同时把B、C添加到A 的 childViewControllers ,然后当A显示时,发现B、C的viewWillAppear、viewDidAppear、viewWillDisappear、viewDidDisappear全都失效了。最终的解决方案如下:
在A中执行如下操作就可以解决了

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.childViewControllers.forEach {
        $0.beginAppearanceTransition(true, animated: animated)
    }
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.childViewControllers.forEach {
        $0.endAppearanceTransition()
    }
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    self.childViewControllers.forEach {
        $0.beginAppearanceTransition(false, animated: animated)
    }
}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    self.childViewControllers.forEach {
        $0.endAppearanceTransition()
    }
}

最后大家看一下官方文档关于,open func beginAppearanceTransition,open func endAppearanceTransition()的解释

If a custom container controller manually forwards its appearance callbacks, then rather than calling
viewWillAppear:, viewDidAppear: viewWillDisappear:, or viewDidDisappear: on the children these methods
should be used instead. This will ensure that descendent child controllers appearance methods will be
 invoked. It also enables more complex custom transitions to be implemented since the appearance callbacks are
 now tied to the final matching invocation of endAppearanceTransition.

大概意思是,如果父容器要发生改变,不是直接调用子视图的方法,而是用这些来替代使用,这样可以确保子视图也将执行对应的方法,去改变视图本身。

open func beginAppearanceTransition(_ isAppearing: Bool, animated: Bool)

isAppearing:true:子视图即将显示;false:子视图即将消失,所以在viewWillAppear为true,viewWillDisappear为false

open func endAppearanceTransition()

beginAppearanceTransition成对出现,完成后调用即可

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,935评论 8 265
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 11,857评论 0 17
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,850评论 19 139
  • 生命是一个不可思议的东西。 人的生命因为被上天赋予了观察力、聆听力、思考力、表达力、创造力, 在生灵万物之中应该更...
    光中的cici阅读 1,891评论 0 3
  • 两年前,何英优异的成绩,考取了本镇最好的莫华高中。她被分到高一(3)班。班上有个叫梅子的女生,齐耳短发,模样清秀,...
    QIYU098阅读 4,342评论 32 66

友情链接更多精彩内容