UILongPressGestureRecognizer - Image zoom in and out example on Long Press Gesture in swift - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

16 Nov 2017

UILongPressGestureRecognizer - Image zoom in and out example on Long Press Gesture in swift

In this tutorial we will learn how to zoom in and out an imageView using UILongPressGestureRecognizer.

The iOS UILongPressGestureRecognizer class has a built-in way to detect long press gesture on any view.

UILongPressGestureRecognizer - Image zoom in and out example on Long Press Gesture in swift gif

Other Gestures in iOS:


Getting Started:

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

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
view.addSubview(imageView)
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 Long Press Gesture:

First create an instance to UILongPressGestureRecognizer() as follow:

var longPressGesture = UILongPressGestureRecognizer()

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

longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressGestureHandler))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(longPressGesture)

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 long press gesture, add the following method:

@objc func longPressGestureHandler(recognizer:UIPinchGestureRecognizer){
    switch recognizer.state {
    case .began:
        UIView.animate(withDuration: 0.05,
                       animations: {
                        self.imageView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
        },
                       completion: nil)
    case .ended:
        UIView.animate(withDuration: 0.05) {
            self.imageView.transform = CGAffineTransform.identity
        }
    default: break
    }
}

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

Tap on image and hold for 1 sec we will see image zoom in as follow:

UILongPressGestureRecognizer - Image zoom in and out example on Long Press Gesture in swift

Download sample project with example :

No comments:

Post a Comment

Post Top Ad