iOS中UIView的Pan手勢和UIScrollView滾動手勢的沖突解決方案


tableView滾動視圖中包含播放器窗口,播放器控制層包含了上下滑動手勢調節音量和屏幕亮度功能,與tableView的上下滾動手勢沖突。導致播放器窗口上下滾動時,tableView不滾動問題,影響用戶體驗。

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

新建 UIPanGestureRecognizer的子類 

@interface ZFPanGestureRecognizer : UIPanGestureRecognizer

/**
 是否自動鎖住手勢方向,默認為NO
 如果設置成YES,則在手勢開始時根據xy的偏移量大小來確定最可能的滑動方向,並在手勢有效期內保持這個方向上的有效性
 */
@property (nonatomic, assign) BOOL  autoLock;

@end

然后實現touchesMoved方法,可以在該方法中自定義,是否支持滑動效果。

#import "ZFPanGestureRecognizer.h"

typedef NS_ENUM(NSInteger, IXPanDirection) {
    IXPanDirectionAny = 0,
    IXPanDirectionHor,
    IXPanDirectionVer
};

@interface ZFPanGestureRecognizer ()

@property (nonatomic, assign) IXPanDirection    direction;
@property (nonatomic, assign) CGPoint   beginP;

@end

@implementation ZFPanGestureRecognizer

-(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 {
            if (_beginP.x > self.view.bounds.size.width*0.5) {
                _direction = IXPanDirectionVer;
                self.state = UIGestureRecognizerStateFailed;
            }
        }
    }
}

使用我們的自定義pan手勢

ZFPanGestureRecognizer * ixPan = [[ZFPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)]; 
ixPan.autoLock
= YES;
[view addGestureRecognizer:ixPan];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM