UIPanGestureRecognizer - Dragging View Example in Swift - Swift 4 Tutorials W3Schools


Post Top Ad

15 Nov 2017

UIPanGestureRecognizer - Dragging View Example in Swift

In this tutorial we will learn how to drag a view using UIPanGestureRecognizer.

The iOS UIPanGestureRecognizer class has a built-in way to detect pan gesture on any view.

UIPanGestureRecognizer - Dragging View Example in Swift

Other Gestures in iOS:

Single Tap & Double Tap Gesture - UITapGestureRecognizer
Swipe Gesture Recognizer - UISwipeGestureRecognizer
Pinch Gesture Recognizer - UIPinchGestureRecognizer
Long Press Gesture - UILongPressGestureRecognizer
UIRotationGestureRecognizer - Rotate Image View swift

Getting Started:

Firstly create new Xcode project and save it with 'PanGesture'.

Next open the ViewController.swift file and add the imageView as follow.

Adding ImageView:

First create imageView property as follow:

let imageView = UIImageView()

Next add imageView as sub view and give the auto layout constraints. Add the following code in viewDidLoad() method:

imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = UIImage(named: "cat")
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
imageView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.4).isActive = true
imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: 1).isActive = true

Adding Pan Gesture:

First create an instance to UIPanGestureRecognizer() as follow:

var panGesture  = UIPanGestureRecognizer()

Next add panGesture to the imageView. Add the following code to the end of viewDidLoad() method:

panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.panGestureHandler(_:)))
imageView.isUserInteractionEnabled = true

The isUserInteractionEnabled property of the view is set to true. Image views and labels set this property to false by default.

Finally add the action for the pan gesture, add the following method:

@objc func panGestureHandler(_ recognizer: UIPanGestureRecognizer){
    self.view.bringSubview(toFront: imageView)
    let translation = recognizer.translation(in: self.view)
    imageView.center = CGPoint(x: imageView.center.x + translation.x, y: imageView.center.y + translation.y)
    recognizer.setTranslation(CGPoint.zero, in: self.view)

Run the project, we will see an image with an pan gesture as follow:

UIPanGestureRecognizer - Dragging View Example in Swift

Download sample project with example :

No comments:

Post a Comment

Post Top Ad