UILongPressGestureRecognizer长按手势事件不响应


最近发现项目中有多处列表页都不能侧滑返回,公司没有产品经理,这样对于8P这样的屏幕体验非常的差, 我就添加统一的侧滑返回,期间遇到遇见一个有关长按手势不执行的问题。

问题描述:

给UITableView的cell添加了长按手势,当长按cell时UILongPressGestureRecognizer事件不响应,只有手指移动和手指松开时长按事件才会被执行

问题排查

初步判断多个手势冲突, 问题应该由添加侧滑返回的代码出现了问题,侧滑返回我使用了UINavigationController+TZPopGesture分类,通过一个方法即可实现。 查看其实现,发现它是给scrollView添加一个UIPanGestureRecognizer拖动手势,当这个拖动手势响应时,执行navigationController的侧滑返回手势,触发侧滑返回, 另外还在UINavigationController中 实现了self.interactivePopGestureRecognizer.delegate; 我发现问题应该出在这块,便注释了部分手势的代理方法,发现tableViewCell的长按手势可正常响应了; 最终确定问题发生在- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer方法内, 最初的时候为了解决只有在系统侧滑手势失败时,才去触发ScrollView的滑动,此方法return YES;

此方法有两个参数为两个手势,意思为只有当gestureRecognizer被判断侦测失败了,才可以侦测otherGestureRecognizer, 当我长按cell时,长按手势为otherGestureRecognizer,而此时gestureRecognizer为我们为scrollView添加的拖动手势,那此时拖动手势并没有失败,所以长按手势不会被执行到,但当手指移动或松开时gestureRecognizer被侦测失败,此时otherGestureRecognizer长按手势才会被侦测到;

解决方法

处理添加的侧滑返回手势和长按手势冲突,当当前手势gestureRecognizer是侧滑返回手势时,同时处理otherGestureRecognizer

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    // 此处导致使用此分类的界面长按时不能及时响应,只有手指移动、松开手指时才会响应长按手势
    UIViewController *vc = self.topViewController;
    if ([gestureRecognizer isEqual:vc.tz_popGestureRecognizer]) {
        return NO;
    }
    return YES;
}

总结

  • 通过Xcode文档发现,这两个api是在iOS7时添加的
// called once per attempt to recognize, so failure requirements can be determined lazily and may be set up between recognizers across view hierarchies
// return YES to set up a dynamic failure requirement between gestureRecognizer and otherGestureRecognizer
//
// note: returning YES is guaranteed to set up the failure requirement. returning NO does not guarantee that there will not be a failure requirement as the other gesture's counterpart delegate or subclass methods may return YES
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer NS_AVAILABLE_IOS(7_0);
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer NS_AVAILABLE_IOS(7_0);
  • 说明
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer NS_AVAILABLE_IOS(7_0);

此方法指定只有gestureRecognizer被系统判定失败时,才会执行otherGestureRecognizer

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer NS_AVAILABLE_IOS(7_0);

此方法指定只有otherGestureRecognizer被系统判定失败时,才会执行gestureRecognizer

由于这两个方法比较相似,所以用的时候还是要注意使用场景,不要弄混了。

附件: