iOS技术专题

iOS 实现全屏右滑返回

2018-09-05  本文已影响239人  Feroo_J

1.系统右滑返回

在开发中,当push到一个新控制器的时候,系统自带了一个右滑返回的手势,不过这个手势只能是在屏幕的左边缘才有效果,如果新的控制器隐藏了导航控制器,系统的右滑返回就没有效果了,如果仍然需要右滑返回效果,则需添加下面两行代码:

navigationController?.interactivePopGestureRecognizer?.delegate = self  //记得遵守 UIGestureRecognizerDelegate 协议
navigationController?.interactivePopGestureRecognizer?.isEnabled = true

系统右滑返回虽然已经比较方便了,但是它受限于两个点:只有从屏幕左边缘滑动才有效果、受导航栏的显示隐藏影响。为了解决这两个限制,我们需要自己来实现全屏右滑返回。

2.全屏右滑返回

思路:在基类导航控制器中,用自定义手势替换系统手势,同时将系统手势对应的target-action赋值给自定义手势。

代码量很少,先上代码:

import UIKit

class CustomNavigationController: UINavigationController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //1.获取系统右滑手势对应的 target 和 action
        
        //1.1 获取系统右滑返回手势
        guard let systemGesture = interactivePopGestureRecognizer else { return }
        
        //1.2获取手势对应的 target-action 对象
        let targets = systemGesture.value(forKey: "_targets") as? [NSObject]
        guard let targetObjc = targets?.first else { return }
        
        //1.3获取target
        guard let target = targetObjc.value(forKey: "target") else { return }
        
        //1.4获取action
        let action = Selector(("handleNavigationTransition:"))
        
        //2.创建自定义手势,并赋值 target, action
        let customGesture = UIPanGestureRecognizer()
        customGesture.addTarget(target, action: action)
        
        //3.将自定义手势添加到系统手势的view上
        guard let gestureView = systemGesture.view else { return }
        gestureView.addGestureRecognizer(customGesture)
        
    }
}

其实也就三个步骤:
(1) 获取系统右滑手势对应的 target 和 action
(2) 创建自定义手势,并赋值 target, action
(3) 将自定义手势添加到系统手势的view上
主要是第一步拿 target 和 action比较麻烦一些,代码里面有具体的注释。这样就实现了全屏幕右滑返回效果,并且不会受到导航栏的显示和隐藏所影响,希望能帮助到需要的同学。

上一篇 下一篇

猜你喜欢

热点阅读