UIRotationGestureRecognizer - Rotate image with Two Fingers in swift - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

18 Nov 2017

UIRotationGestureRecognizer - Rotate image with Two Fingers in swift

In this tutorial we will learn how to rotate an imageView using UIRotationGestureRecognizer.

A rotation gesture is a continuous gesture that occurs when the first two fingers that touch the screen rotate around each other

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

UIRotationGestureRecognizer - Rotate image with Two Fingers in swift

Other Gestures in iOS:

Getting Started:

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

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.6).isActive = true
imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: 1).isActive = true

Adding Rotation Gesture:

First create an instance to UIRotationGestureRecognizer() as follow:

var rotationGesture = UIRotationGestureRecognizer()

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

rotationGesture = UIRotationGestureRecognizer(target: self, action: #selector(self.rotationGestureHandler))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(rotationGesture)

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

@objc func rotationGestureHandler(recognizer:UIRotationGestureRecognizer){
    if let view = recognizer.view {
        view.transform = view.transform.rotated(by: recognizer.rotation)
        recognizer.rotation = 0
    }
}

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

UIRotationGestureRecognizer - Rotate image with Two Fingers in swift-gif
Download sample project with example :

1 comment:

  1. บริการเกมสล็อตออนไลน์ปี 2022 เกมให้เลือกเล่นมากกว่า 1,000 เกมสล็อตออนไลน์ d

    ReplyDelete

Post Top Ad