[英]Overriding back swipe gesture in UINavigationController
How to override gesture to pop to rootViewController, not to previous ViewController?如何覆盖手势以弹出到 rootViewController,而不是以前的 ViewController?
You can do this in a combination of the following:您可以结合以下方式执行此操作:
Add a swipe gesture recognizer to your view controller:向您的视图控制器添加滑动手势识别器:
Add the following to your view controller class:将以下内容添加到您的视图控制器类:
import UIKit
class SwipeBackViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
}
@IBAction func swipeback(_ sender: UISwipeGestureRecognizer) {
navigationController?.popToRootViewController(animated: true)
}
}
viewDidLoad
disables the default swipe recogninzer in iOS viewDidLoad
的命令禁用了 iOS 中的默认滑动识别器My answer here goes into disabling the recognizer in more detail in case you have any questions on that.我的答案在这里进入的情况下,禁用识别更详细你有任何问题。
I followed CodeBender's answer but the swipeback
function didn't call.我遵循了 CodeBender 的回答,但没有调用
swipeback
功能。
After add self.view.addGestureRecognizer(backswipeGestureRecognizer)
in viewDidLoad()
, it works.在
viewDidLoad()
添加self.view.addGestureRecognizer(backswipeGestureRecognizer)
后,它起作用了。
Also, you can set delegate of this gesture in viewController, in viewController's viewDidLoad.此外,您可以在 viewController 的 viewDidLoad 中设置此手势的委托。 It looks like:
看起来像:
override func viewDidLoad() {
super.viewDidLoad()
navigationController.interactivePopGestureRecognizer?.delegate = self
}
and customize it's methods in view controller. For example:并在视图 controller 中自定义它的方法。例如:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive event: UIEvent) -> Bool {
print("event \(event.description)")
return true
} }
If you set returning value for false - pop action will not be triggered如果您将返回值设置为 false - 将不会触发弹出操作
For me it worked like:对我来说,它的工作方式如下:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive event: UIEvent) -> Bool {
showAlertViewController()
return false
} }
If you need this behaviour only once, you should set delegate back in viewController's deinit method如果你只需要一次这种行为,你应该在 viewController 的 deinit 方法中重新设置委托
deinit {
navigationController?.interactivePopGestureRecognizer?.delegate = navigationController
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.