UIPanGestureRecognizer 弹出 UIViewController

UIPanGestureRecognizer to pop UIViewController

我想知道是否真的可以在推送的 UIViewController 上使用 UIPanGestureRecognizer 来实现类似于 Telegram Messenger 聊天视图(以及许多其他流行的应用程序)中的类似行为),您只需从屏幕上的任意位置向右滑动即可返回菜单(或任何其他最初推送我们正在查看的视图控制器的视图控制器)。
我试过这段代码:

    @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
        }
    }
}

和一个 UIPanGestureRecognizer,如果您 present 编辑了您的 ViewController,它确实可以很好地工作,但在它被推送时却不行。至少现在不是这样。

现在,您看到一个黑色视图,这也是您在推送 UIViewController 底部的 "Debug View Hirachy" 中看到的内容ViewController。

感谢任何帮助!

我想你要找的已经 built-in 和 interactivePopGestureRecognizer

self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true

如果您想制作一些自定义或不同的动画,那么我认为您需要检查转换。这是进行自定义转换的好文章: https://medium.com/swift2go/simple-custom-uinavigationcontroller-transitions-fdb56a217dd8

无需处理平移手势。 您可以将您的视图嵌入导航控制器,它会提供这样的行为(滑动返回)。

然后如果不想看到导航栏也可以隐藏。

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)

我刚刚创建了一个 Pod,以便在导航控制器上具有这种 Telegram/Instagram-like Pan-to-pop 行为。

可以看到here

它允许用户:

  • Pan-to-pop 通常从左边缘开始(像每个正常的 UINavigationController
  • Pan-to-pop 从没有 scrollView 或其他 panGesture 干扰的中心开始
  • Pan-top-pop 在任何滚动视图的顶部,如果它们位于 offset.x = 0(因此它的行为类似于 Instagram)

所有这一切,同时保留导航控制器的所有默认功能。

要使用 CocoaPods 安装它,只需将 pod 包含在 Podfile 中:

pod 'EZCustomNavigation', '1.0.0'

要使用它,只需使用 EZNavigationController 而不是默认的 UINavigationController 就可以了。