1.背景
我们有个页面,会在里面进行一些操作,然后退出的时候,如果满足条件,需要弹一个alert提醒用户进行保存数据。用户除了可以通过左上角的返回按钮返回上一级页面,还可以通过iOS的侧滑返回手势返回,所以我们对侧滑返回手势,需要着重处理一下。
2.方案
我的方案就是自己定义一个全屏返回手势,如下
var fullScreenPopPanGesture: UIPanGestureRecognizer?
用这个手势替换掉系统的侧滑手势
private func customPopGesture() {
let action = Selector("handleNavigationTransition:")
fullScreenPopPanGesture = UIPanGestureRecognizer(target: navigationController?.interactivePopGestureRecognizer?.delegate, action: action)
fullScreenPopPanGesture?.delegate = self
guard let tempPop = fullScreenPopPanGesture else { return }
view.addGestureRecognizer(tempPop)
navigationController?.interactivePopGestureRecognizer?.require(toFail: tempPop)
}
然后在手势的系统代理方法里对手势进行处理,符合条件(canPopBackAction),且是从左到右滑动,那么就弹弹窗。具体的条件,看自己需求。
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.isEqual(fullScreenPopPanGesture) {
let translation = fullScreenPopPanGesture?.translation(in: fullScreenPopPanGesture?.view)
let isLeftToRight = UIApplication.shared.userInterfaceLayoutDirection == UIUserInterfaceLayoutDirection.leftToRight
let multiplier: CGFloat = isLeftToRight ? 1.0 : -1.0
let isLeft = ((translation?.x ?? 0) * multiplier > 0.0)
if !canPopBackAction(), isLeft {
// 是从左到右,而且满足自定义的条件,则弹alert
showLimitAlert()
}
return canPopBackAction()
}
return true
}
3.总结
总结起来,就是我们通过自定义的全屏手势,替换了系统的侧滑返回手势,然后在gestureRecognizerShouldBegin函数里,判断从左往右的手势,最后根据我们的业务需求,决定要不要响应。