我想知道是否真的可以在推送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
视图控制器,但在推送时效果不佳,它确实可以很好地工作。至少不是现在的样子。
现在,您会看到一个黑色视图,这也是您在推送的UIViewController底部的"调试视图Hirachy"中看到的。
任何帮助不胜感激!
我认为您正在寻找的内容已经内置在interactivePopGestureRecognizer
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
如果您想制作一些自定义或不同的动画,那么我认为您需要检查过渡。这是一篇进行自定义转换的好文章:https://medium.com/swift2go/simple-custom-uinavigationcontroller-transitions-fdb56a217dd8
无需处理平移手势。您可以将视图嵌入到导航控制器中,它将提供此类行为(滑动返回(。
然后,如果您不想看到导航栏,也可以隐藏它。
用户还可以使用背面移除最顶层的视图控制器 按钮或使用左边缘轻扫手势。
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 的 Pan-to-pop 行为。
你可以在这里看到它
它允许用户:
- 通常从左边缘
Pan-to-pop
(像每个普通UINavigationController
一样( - 从中心
Pan-to-pop
,没有滚动视图或其他干扰的平移手势 -
Pan-top-pop
在任何滚动视图的顶部,如果它们位于 offset.x = 0(因此它的行为类似于 Instagram(
所有这些都保留了导航控制器的所有默认功能。
要使用 CocoaPods 安装它,只需将 pod 包含在 Podfile 中:
pod 'EZCustomNavigation', '1.0.0'
要使用它,只需使用 EZNavigationController
而不是默认UINavigationController
,它应该就可以工作了。