iOS UIPanGestureRecognizer


Example

Pan gesture recognizers detect dragging gestures. The following example adds an image to a view controller and lets the user drag it around on screen.

Objective-C

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"imageToDrag"]];
    [imageView sizeToFit];
    imageView.userInteractionEnabled = YES;
    [self.view addSubview:imageView];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [imageView addGestureRecognizer:pan];
}

- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    CGPoint translation = [recognizer translationInView:self.view];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointZero inView:self.view];
}

Swift

override func viewDidLoad() {
    super.viewDidLoad()
    
    let imageView = UIImageView.init(image: UIImage.init(named: "imageToDrag"))
    imageView.sizeToFit()
    imageView.isUserInteractionEnabled = true
    self.view.addSubview(imageView)
    
    let pan = UIPanGestureRecognizer.init(target: self, action: #selector(handlePan(recognizer:)))
    imageView.addGestureRecognizer(pan)
}

func handlePan(recognizer: UIPanGestureRecognizer) {
    let translation = recognizer.translation(in: self.view)
    if let view = recognizer.view {
        view.center = CGPoint(x: view.center.x + translation.x, y: view.center.y + translation.y)
    }
    recognizer.setTranslation(CGPoint.zero, in: self.view)
}

Note: Although UIPanGestureRecognizer is useful for detecting any dragging gestures, if you just want to detect a basic gesture such as user dragging their finger left/right or up/down, use UISwipeGestureRecognizer. UIPanGestureRecognizer is a better choice if you need access to methods such as translationInView: or velocityInView:.