Swift:解決ViewController中viewWillAppear失效的問(wèn)題

最近做了一個(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)用即可

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1.ios高性能編程 (1).內(nèi)層 最小的內(nèi)層平均值和峰值(2).耗電量 高效的算法和數(shù)據(jù)結(jié)構(gòu)(3).初始化時(shí)...
    歐辰_OSR閱讀 30,243評(píng)論 8 265
  • ¥開(kāi)啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開(kāi)一個(gè)線(xiàn)程,因...
    小菜c閱讀 7,334評(píng)論 0 17
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,568評(píng)論 19 139
  • 生命是一個(gè)不可思議的東西。 人的生命因?yàn)楸簧咸熨x予了觀察力、聆聽(tīng)力、思考力、表達(dá)力、創(chuàng)造力, 在生靈萬(wàn)物之中應(yīng)該更...
    光中的cici閱讀 329評(píng)論 0 3
  • 兩年前,何英優(yōu)異的成績(jī),考取了本鎮(zhèn)最好的莫華高中。她被分到高一(3)班。班上有個(gè)叫梅子的女生,齊耳短發(fā),模樣清秀,...
    QIYU098閱讀 944評(píng)論 32 66

友情鏈接更多精彩內(nèi)容