1. 程式人生 > >iOS PanGesture和ScrollView的手勢衝突解決方案

iOS PanGesture和ScrollView的手勢衝突解決方案

之前擼k線,k線檢視作為一個子控制元件被放在了ScrollView上,由於k線有個左右滑動的手勢,於是使用了UIPanGestureRecognizer,這導致了在K線上上下滑動時ScrollView沒有任何相應,在互動上不太友好。

因此本內容主要是為了處理UIScrollView的子檢視上新增UIPanGestureRecognizer後,導致上下滑動該子檢視時UIScrollView無法跟隨上下滾動的情況。

實現原理
新建UIPanGestureRecognizer子類
重寫- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

方法
在此方法中,根據手勢方向處理手勢的有效性。

核心程式碼

@implementation IXPanGestureRecognizer

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];

    if (_autoLock) {
        _direction = IXPanDirectionAny;
        _beginP = [[touches anyObject] locationInView:self
.view]; } } - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [super touchesMoved:touches withEvent:event]; if (!_autoLock && _direction != IXPanDirectionAny) return; CGPoint nowPoint = [[touches anyObject] locationInView:self.view]; if
(_direction == IXPanDirectionAny) { if (fabs(nowPoint.x - _beginP.x) > fabs(nowPoint.y - _beginP.y)) { _direction = IXPanDirectionHor; } else { _direction = IXPanDirectionVer; self.state = UIGestureRecognizerStateFailed; } } } @end

如有疑問可檢視demo