最近做了一个功能,大概是这样的,把 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
成对出现,完成后调用即可