UIPanGesture跟随手势滑动View

2021-11-04  本文已影响0人  独孤流

记录一个平常很常见的代码段,某些弹窗需要可以跟随手势滑动拖拽

#import "TestDragPanView.h"

@implementation TestDragPanView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panMoved:)];
        pan.minimumNumberOfTouches = 1;
        pan.maximumNumberOfTouches = 1;
        [self addGestureRecognizer:pan];
    }
    return self;
}
- (void)panMoved:(UIPanGestureRecognizer *)panGesture {
    if (panGesture.state == UIGestureRecognizerStateEnded
        || panGesture.state == UIGestureRecognizerStateCancelled
        || panGesture.state == UIGestureRecognizerStateFailed) {
        // 当停止移动时,设置自动移动到边侧
        // 一般panGesture.view 等同于self
        UIView *gestureView = panGesture.view;
        CGFloat autoMinX = 50;
        CGFloat autoMaxX = UIScreen.mainScreen.bounds.size.width - gestureView.frame.size.width - 50;
        CGFloat originX = gestureView.frame.origin.x;
        if (originX < autoMinX) {
            // 当停下来时,x超过一定的数据,自动靠到左边
            CGFloat fix = 0;
            gestureView.frame = CGRectMake(fix, gestureView.frame.origin.y, gestureView.frame.size.width, gestureView.frame.size.height);
        }else if (gestureView.frame.origin.x > autoMaxX) {
            // 当停下来时,x超过一定的数据,自动靠到右边
            CGFloat fix = UIScreen.mainScreen.bounds.size.width - gestureView.frame.size.width;
            gestureView.frame = CGRectMake(fix, gestureView.frame.origin.y, gestureView.frame.size.width, gestureView.frame.size.height);
        }
        
    }else if(panGesture.state == UIGestureRecognizerStateChanged) {
        // 一般panGesture.view 等同于self
        UIView *gestureView = panGesture.view;
        // 获取到手指移动的距离
        CGPoint translation = [panGesture translationInView:gestureView.superview];
        // 限定centerX的最大最小值
        CGFloat minCenterX = gestureView.bounds.size.width/2;
        CGFloat maxCenterX = UIScreen.mainScreen.bounds.size.width - gestureView.bounds.size.width/2;
        CGFloat centerX = gestureView.center.x + translation.x;
        centerX = MAX(minCenterX, centerX);
        centerX = MIN(maxCenterX, centerX);
        // 限定centerY的最大最小值
        CGFloat minCenterY = gestureView.bounds.size.height/2;
        CGFloat maxCenterY = UIScreen.mainScreen.bounds.size.height - gestureView.bounds.size.height/2;
        CGFloat centerY = gestureView.center.y + translation.y;
        centerY = MAX(minCenterY, centerY);
        centerY = MIN(maxCenterY, centerY);
        // 设置最新center,实现view跟随view移动
        gestureView.center = CGPointMake(centerX, centerY);
        // 将手势移动的距离恢复成0,这样可以在下次读取移动距离时比较简单
        [panGesture setTranslation:CGPointZero inView:gestureView.superview];
    }
     
}

@end
oytwy-ssmbh (1).gif
上一篇下一篇

猜你喜欢

热点阅读