最近做了一個(gè)功能,大概是這樣的,把 ViewController B、ViewController C...... 的view 添加到ViewController A中,同時(shí)把B、C添加到A 的 childViewControllers ,然后當(dāng)A顯示時(shí),發(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)用子視圖的方法,而是用這些來(lái)替代使用,這樣可以確保子視圖也將執(zhí)行對(duì)應(yīng)的方法,去改變視圖本身。
open func beginAppearanceTransition(_ isAppearing: Bool, animated: Bool)
isAppearing:true:子視圖即將顯示;false:子視圖即將消失,所以在viewWillAppear為true,viewWillDisappear為false
open func endAppearanceTransition()
與beginAppearanceTransition成對(duì)出現(xiàn),完成后調(diào)用即可