iOS UIPanGestureRecognizer

 



UIPanGestureRecognizer负责拖动手势。
#import "MyView.h"


@interface MyView()

//@property(assign, nonatomic) CGPoint startTouchPosition;
@property(assign, nonatomic) CGRect initFrame;

@end

@implementation MyView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.initFrame = frame;
        [self setGesture];
        self.backgroundColor = [UIColor grayColor];
    }
    return self;
}

- (void)setGesture{
    UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleDrag:)];
    [self addGestureRecognizer:panGR];
}

- (void)handleDrag:(UIPanGestureRecognizer*) recgonizer{
    CGPoint point =
    [recgonizer translationInView:nil];//不传参数表示坐标系是当前窗口(指当前的UIWindow,不是指view)
    CGFloat dltX = point.x;
    CGFloat dltY = point.y;
    [recgonizer setTranslation:CGPointZero inView:nil];//由于translationInView表示此次移动的位移,如果不重置就会越来越大,导致拖动越来越快。
self.center = CGPointMake(self.center.x + dltX, self.center.y + dltY); NSLog(@"拖动中"); } @end

或者可以这样简单实现handleDrag方法:

- (void)handleDrag:(UIPanGestureRecognizer*) recgonizer{
    CGPoint point =
    [recgonizer locationInView:nil];
    self.center = point;
    NSLog(@"拖动中");
}

因为locationInView是返回坐标的,不传参数表示坐标系就是当前窗口。

posted @ 2020-12-21 20:05  NeoZy  阅读(269)  评论(0编辑  收藏  举报