当我们使用了系统的导航栏时,默认点击返回按钮是 pop 回上一个界面。但是在有时候,我们需要在点击导航栏的返回按钮时不一定要 pop 回上一界面,比如一个视频播放界面,进入横屏后,默认点击返回按钮仍然是 pop 返回上一个界面,但是如果我们想要在横屏点击返回按钮的时候是返回竖屏模式,而不是 pop 到上一界面,这该怎么实现呢?
然而网上的栗子都是OC语言下写的类拓展,找了半天找不到swift,我不知道swift是否有这种方便的类拓展,下面只是简单的写在控制器里面。
extension MTProfileCompanyModifyViewController: UINavigationBarDelegate {
func navigationShouldPopOnBackButton() -> Bool {
let alertController = UIAlertController(title: nil, message: "您的公司信息尚未完善,确定返回吗?", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "继续编辑", 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 后,复原返回按钮的状态
/*__系统返回按钮会随着返回动画而边淡__*/
for subView in navigationBar.subviews {
if subView.alpha < 1.0 {
UIView.animate(withDuration: 0.25, animations: {
subView.alpha = 1.0
})
}
}
}
return false
}
}
参考链接:iOS拦截导航栏返回按钮事件的正确方式