swift 攔截導(dǎo)航欄返回按鈕事件

當(dāng)我們使用了系統(tǒng)的導(dǎo)航欄時(shí),默認(rèn)點(diǎn)擊返回按鈕是 pop 回上一個(gè)界面。但是在有時(shí)候,我們需要在點(diǎn)擊導(dǎo)航欄的返回按鈕時(shí)不一定要 pop 回上一界面,比如一個(gè)視頻播放界面,進(jìn)入橫屏后,默認(rèn)點(diǎn)擊返回按鈕仍然是 pop 返回上一個(gè)界面,但是如果我們想要在橫屏點(diǎn)擊返回按鈕的時(shí)候是返回豎屏模式,而不是 pop 到上一界面,這該怎么實(shí)現(xiàn)呢?

然而網(wǎng)上的栗子都是OC語(yǔ)言下寫(xiě)的類拓展,找了半天找不到swift,我不知道swift是否有這種方便的類拓展,下面只是簡(jiǎn)單的寫(xiě)在控制器里面。


extension MTProfileCompanyModifyViewController: UINavigationBarDelegate {
    
    
    func navigationShouldPopOnBackButton() -> Bool {
        let alertController = UIAlertController(title: nil, message: "您的公司信息尚未完善,確定返回嗎?", preferredStyle: .alert)
        let alertAction = UIAlertAction(title: "繼續(xù)編輯", style: .default) { (_) in
            
        }
        alertController.addAction(alertAction)
        let cancelAction = UIAlertAction(title: "放棄修改", style: .cancel) { (_) in
            self.navigationController?.popViewController(animated: true)
        }
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
        return false
    }
    
    func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
     
        if (self.navigationController?.viewControllers.count ?? 0) < (navigationBar.items?.count ?? 0) {
            return true
        }
        shouldPop = self.navigationShouldPopOnBackButton()
        if shouldPop {
            DispatchQueue.main.async() {
                self.navigationController?.popViewController(animated: true)
            }
        } else {
            // 取消 pop 后,復(fù)原返回按鈕的狀態(tài)
            /*__系統(tǒng)返回按鈕會(huì)隨著返回動(dòng)畫(huà)而邊淡__*/
            for subView in navigationBar.subviews {
                if subView.alpha < 1.0 {
                    UIView.animate(withDuration: 0.25, animations: { 
                        subView.alpha = 1.0
                    })
                }
            }
        }
        return false
    }
    
}

參考鏈接:iOS攔截導(dǎ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)容

  • 當(dāng)我們使用了系統(tǒng)的導(dǎo)航欄時(shí),默認(rèn)點(diǎn)擊返回按鈕是 pop 回上一個(gè)界面。但是在有時(shí)候,我們需要在點(diǎn)擊導(dǎo)航欄的返回按鈕...
    乒什么乓閱讀 40,786評(píng)論 29 76
  • 下班回到家,俊豪明哲和奶奶在家玩。我先給俊豪發(fā)了視頻,發(fā)完視頻檢查作業(yè),昨天兒子考試了,今天發(fā)了試卷,語(yǔ)...
    天使在唱歌_6d35閱讀 250評(píng)論 0 0
  • 一直以來(lái)缺少思考的習(xí)慣,忙碌時(shí)沒(méi)時(shí)間,等到空閑時(shí)有沒(méi)心情,一門(mén)心思鉆在影視劇里去填充空洞的內(nèi)心,在以前沒(méi)感覺(jué)出什...
    燈火點(diǎn)亮人生閱讀 367評(píng)論 0 0
  • It must have been a terrible moment for the Witch when sh...
    Mr_Oldman閱讀 516評(píng)論 0 0
  • 我在讀初中的時(shí)候就喜歡看書(shū),所以一直到大學(xué)畢業(yè),這期間我陸陸續(xù)續(xù)的看過(guò)很多書(shū)。雖然書(shū)看的多,但我就是那個(gè)讀了這么多...
    周周周云閱讀 385評(píng)論 6 4

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