UINavigationController 返回手勢與 leftBarButtonItem UINavigationController 自帶從屏幕左側邊緣向右滑動的返回手勢,可以通過這個手勢實現 pop,或者 pop 中途取消 pop 而停留在當前控制器(UIViewController)。如果 ...
UINavigationController 返回手勢與 leftBarButtonItem
UINavigationController 自帶從屏幕左側邊緣向右滑動的返回手勢,可以通過這個手勢實現 pop,或者 pop 中途取消 pop 而停留在當前控制器(UIViewController)。如果設置了當前控制器的 navigationItem.leftBarButtonItem 或 navigationItem.leftBarButtonItems,則返回手勢失效。可以通過自定義 NavigationController,實現設置 navigationItem.leftBarButtonItem 或 navigationItem.leftBarButtonItems,並且保留返回手勢。代碼已上傳 GitHub:https://github.com/Silence-GitHub/NavigationControllerDemo
UINavigationController 的 interactivePopGestureRecognizer 屬性為返回手勢。設置手勢的 delegate,手動管理返回手勢。當 UINavigationController 沒有或只有一個子控制器時,返回手勢不能響應,否則會出現奇怪的現象。自定義 currentNotRootVC 屬性,記錄當前的非根子控制器(只有一個子控制器時,此子控制器為根子控制器,root view controller)。設置 UINavigationController 的 delegate,通過 UINavigationControllerDelegate 的方法,更新 currentNotRootVC。代碼示例如下
import UIKit
class NavigationController: UINavigationController, UINavigationControllerDelegate, UIGestureRecognizerDelegate {
// Current child view controller, but not root view controller
private var currentNotRootVC: UIViewController?
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
interactivePopGestureRecognizer?.delegate = self
}
// MARK: - UINavigationControllerDelegate
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
currentNotRootVC = viewControllers.count <= 1 ? nil : viewController
/*
switch viewController {
case is SomeVCClassForbidPopGesture:
interactivePopGestureRecognizer?.isEnabled = false
default:
interactivePopGestureRecognizer?.isEnabled = true
}
*/
}
// MARK: - UIGestureRecognizerDelegate
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if interactivePopGestureRecognizer == gestureRecognizer {
// Begin to pop only when top view controller is current child view controller but not root view controller
return currentNotRootVC == topViewController
}
return true
}
}
如果有部分控制器不允許返回手勢(例如編輯信息,退出頁面需要確認),則在func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool)
方法中,加入對 viewController 的判斷,開啟或禁用返回手勢。
參考:http://www.cnblogs.com/v2m_/p/3521569.html
轉載請註明出處:http://www.cnblogs.com/silence-cnblogs/p/6618056.html