问题
I'm wondering if it is actually possible to use a UIPanGestureRecognizer
on a pushed UIViewController
to achieve a similar behaviour like in the Telegram messenger chat view (and a lot of other popular Apps), where you can simply swipe to the right from anywhere on the screen to get back to the menu (or any other View Controller that initially pushed the one we are looking at).
I tried this code:
@objc func swipeLeft(_ sender: UIPanGestureRecognizer) {
let point = sender.translation(in: view)
containerView.center = CGPoint(x: point.x > 0 ? view.center.x + point.x : view.center.x, y: view.center.y)
if sender.state != .ended { return }
if containerView.center.x < view.frame.width / 2 {
dismissSelf()
}
else {
UIView.animate(withDuration: 0.2) {
self.containerView.center = self.view.center
}
}
}
and a UIPanGestureRecognizer
, which does work nicely if you present
ed your ViewController but not when it is pushed. At least not how it is right now.
Right now, you see a black view and that's also what you see in the "Debug View Hirachy" at the bottom of a pushed UIViewController.
Any help is appreciated!
回答1:
I think what you are looking for is already built-in with the interactivePopGestureRecognizer
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
if you want to make some custom or different animation then I think you need to check transitions. Here's a good article to make custom transitions: https://medium.com/swift2go/simple-custom-uinavigationcontroller-transitions-fdb56a217dd8
回答2:
I've just created a Pod to have this Telegram/Instagram-like Pan-to-pop behavior on the navigation controller.
You can see it here
It allows the user to:
Pan-to-pop
normally from the left edge (like every normalUINavigationController
)Pan-to-pop
from the center where there is no scrollView or other panGesture that interferesPan-top-pop
on top of any scrollView if they are at offset.x = 0 (so it behaves like Instagram)
All of this while keeping all the default functionality of the navigation controller.
To install it with CocoaPods just include the pod in the Podfile:
pod 'EZCustomNavigation', '1.0.0'
And to use it just use EZNavigationController
instead of the default UINavigationController
and it should just work.
回答3:
No need of handling pan gesture. you could just embed your view in a navigation controller, and it will provide such behaviour (swipe to go back).
Then you could also hide the navigation bar if you dont want to see it.
The user can also remove the topmost view controller using the back button in the navigation bar or using a left-edge swipe gesture.
https://developer.apple.com/documentation/uikit/uinavigationcontroller
// Hide the Navigation Bar
self.navigationController?.setNavigationBarHidden(true, animated: animated)
// Show the Navigation Bar
self.navigationController?.setNavigationBarHidden(false, animated: animated)
来源:https://stackoverflow.com/questions/56605552/uipangesturerecognizer-to-pop-uiviewcontroller