美文网首页
全局手势返回分析

全局手势返回分析

作者: 宙斯YY | 来源:发表于2018-06-25 16:20 被阅读14次

默认导航控制器管理下的控制器都拥有边缘返回手势。
我们看到UINavigationController.h发现有这个手势的属性
interactivePopGestureRecognizer,该属性是控制该边缘侧滑事件的。
那我们打印出该手势查看一下:

/*
    UIScreenEdgePanGestureRecognizer
    本质是继承UIPanGestureRecognizer手势
    target=<_UINavigationInteractiveTransition 0x7f9e2d40e0e0>
    action=handleNavigationTransition:
*/
self.interactivePopGestureRecognizer:<UIScreenEdgePanGestureRecognizer: 0x7f9e2d473ac0; state = Possible; enabled = NO; delaysTouchesBegan = YES; view = <UILayoutContainerView 0x7f9e2d53e070>; target= <(action=handleNavigationTransition:, target=<_UINavigationInteractiveTransition 0x7f9e2d40e0e0>)>>

但是该手势只作用在发生边缘侧滑的时候,如果我们想实现一个View全局侧滑手势,需要自定义一个UIPanGestureRecognizer手势,实现UIScreenEdgePanGestureRecognizer做的工作,并且禁用系统UIScreenEdgePanGestureRecognizer手势。

- (void)viewDidLoad {
    [super viewDidLoad];

    self.interactivePopGestureRecognizer.enabled=NO;
    //target->self.interactivePopGestureRecognizer.delegate
    //action->handleNavigationTransition:
    UIPanGestureRecognizer * pan=[[UIPanGestureRecognizer alloc]initWithTarget:self.interactivePopGestureRecognizer.delegate action:@selector(handleNavigationTransition:)];
    pan.delegate=self;
    [self.view addGestureRecognizer:pan];    
}

//还得处理自定义手势的代理,如果导航控制器没有自控制器就禁用该手势。
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if(self.childViewControllers.count>0)
    {
        return YES;
    }
    return NO;
}

当然还有一个更简单的办法,FDFullscreenPopGesture第三方库可以不导入一行代码实现全局手势
https://github.com/forkingdog/FDFullscreenPopGesture
它的核心思想就是创建自定义UIPanGestureRecognizer手势,然后通过分类的方式,绑定到UINavigationController中,以下是它的核心代码。

[self.interactivePopGestureRecognizer.view addGestureRecognizer:self.fd_fullscreenPopGestureRecognizer];
NSArray *internalTargets = [self.interactivePopGestureRecognizer valueForKey:@"targets"];
id internalTarget = [internalTargets.firstObject valueForKey:@"target"];
SEL internalAction = NSSelectorFromString(@"handleNavigationTransition:");
self.fd_fullscreenPopGestureRecognizer.delegate = self.fd_popGestureRecognizerDelegate;
[self.fd_fullscreenPopGestureRecognizer addTarget:internalTarget action:internalAction];
self.interactivePopGestureRecognizer.enabled = NO;

相关文章

网友评论

      本文标题:全局手势返回分析

      本文链接:https://www.haomeiwen.com/subject/sbuyyftx.html