Q: 开发过程中遇到一个问题,就是在tableview上下滑动中,其中有一个cell内是添加了Pan滑动手势,导致手指在这个cell中上下滑动,响应了Cell中的手势事件。影响了用户体验。
解决方法:
实现一个UIPanGestureRecognizer创建子类:
@interface DMPanGestureRecognizer : UIPanGestureRecognizer
/**
是否自动锁住手势方向,默认为NO
如果设置成YES,则在手势开始时根据xy的偏移量大小来确定最可能的滑动方向,并在手势有效期内保持这个方向上的有效性
*/
@property (nonatomic, assign) BOOL autoLock;
@end
然后重写touchesMoved方法,可以在该方法中自定义,操作是否支持滑动效果。
typedef NS_ENUM(NSInteger, DMPanDirection) {
DMPanDirectionAny = 0,
DMPanDirectionHor,
DMPanDirectionVer
};
@interface DMPanGestureRecognizer ()
@property (nonatomic, assign) DMPanDirection direction;
@property (nonatomic, assign) CGPoint beginP;
@end
@implementation DMPanGestureRecognizer
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
if (_autoLock) {
_direction = DMPanDirectionAny;
_beginP = [[touches anyObject] locationInView:self.view];
}
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
if (!_autoLock && _direction != DMPanDirectionAny) return;
CGPoint nowPoint = [[touches anyObject] locationInView:self.view];
if (_direction == DMPanDirectionAny) {
if (fabs(nowPoint.x - _beginP.x) > fabs(nowPoint.y - _beginP.y)) {
_direction = DMPanDirectionHor;
} else {
if (_beginP.x > self.view.bounds.size.width*0.5) {
_direction = DMPanDirectionVer;
self.state = UIGestureRecognizerStateFailed;
}
}
}
}
@end
使用方法:
DMPanGestureRecognizer *pan = [[DMPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
pan.autoLock = YES;
[view addGestureRecognizer:pan];