當(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
}
}