最近做了一個功能饺藤,大概是這樣的浮创,把 ViewController B初厚、ViewController C...... 的view 添加到ViewController A中炎码,同時把B忆谓、C添加到A 的 childViewControllers 裆装,然后當(dāng)A顯示時,發(fā)現(xiàn)B倡缠、C的viewWillAppear哨免、viewDidAppear、viewWillDisappear昙沦、viewDidDisappear全都失效了琢唾。最終的解決方案如下:
在A中執(zhí)行如下操作就可以解決了
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()
}
}
最后大家看一下官方文檔關(guān)于,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.
大概意思是,如果父容器要發(fā)生改變盾饮,不是直接調(diào)用子視圖的方法采桃,而是用這些來替代使用,這樣可以確保子視圖也將執(zhí)行對應(yīng)的方法丘损,去改變視圖本身普办。
open func beginAppearanceTransition(_ isAppearing: Bool, animated: Bool)
isAppearing
:true:子視圖即將顯示;false:子視圖即將消失徘钥,所以在viewWillAppear
為true衔蹲,viewWillDisappear
為false
open func endAppearanceTransition()
與beginAppearanceTransition
成對出現(xiàn),完成后調(diào)用即可