Updated 31 August 2021
A UIGestures is called when the user performs a long press. A motion that invokes an action as the drag-event sequence changes. A gesture that recognizes a motion and tracks the angle of the rotation.
UiKit have many gestures recognizer like:-
Now, we are going to know about UIRotationGestureRecognizer. UIRotationGestureRecognizer is a little tricky than other gesture recognizers.
Now, we are going to apply rotation gestures on UIView.
Let’s start
Add UIRotationGestureRecognizer to UIView:
Let’s Create a method that is performing an action when the UIRotationGestureRecognizer detects rotation motion.
1 2 3 |
func rotatedViewAct(_ sender: UIRotationGestureRecognizer) { print("rotation gesture") } |
Now, set it to the gesture recognizer in viewDidLoad function.
1 2 |
let rotateview = UIRotationGestureRecognizer(target: self, action: #selector(rotatedViewAct(_:))) Rotateview.addGestureRecognizer(rotateview) |
Now build, run your project, and try any rotation motions to check the rotatedViewAct method is being called.
Detect States:
In the rotateViewAct method, we can check when the begin, changed, and ended with the gestures recognizer’s property called state.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@objc func rotatedViewAct(_ sender: UIRotationGestureRecognizer) { var lastRotation: CGFloat = 0 var BeginRotation = CGFloat() if sender.state == .began { print("rotation begin") sender.rotation = lastRotation BeginRotation = sender.rotation } else if sender.state == .changed { print("rotation changing") let newRotation = sender.rotation + BeginRotation sender.view?.transform = CGAffineTransform(rotationAngle: newRotation) } else if sender.state == .ended { print("rotation end") lastRotation = sender.rotation } } |
Let’s run it and see this really detects motion states, for instance, when you begin rotation gesture you should see “rotation begin” when rotating see “rotation changing” and when ending rotating see “rotation end”.
Conclusion :
In Conclusion, Gesture Recognizer is easy and more simple when you used it in your application, they ultimately engage a level of user interaction.
Lastly, Please share your thoughts with us in the comment area.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.