Updated 11 December 2023
A pan gesture occurs when the user moves one or more fingers around the device screen. UIPanGestureRecognizer is a concrete subclass of UIGestureRecognizer.
It uses the UIPanGestureRecognizer class for pan gestures and the UIScreenEdgePanGestureRecognizer class for screen-edge pan gestures.
The user must press one or more fingers on a view while panning on the screen.
A panning gesture is on continuous action when the user moves one or more fingers allowed (minimumNumberOfTouches) to enough distance for recognition as a pan.
It changes when the user moves a finger while pressing with the minimum number of fingers. At last, it ends (UIGestureRecognizer.State.ended) when the user lifts all fingers.
1 |
let imageView = UIImageView() |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
func setupImageView() { imageView.isUserInteractionEnabled = true imageView.addGestureRecognizer(panGesture) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.image = UIImage(named: "mobikul") 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 } |
1 |
var panGesture = UIPanGestureRecognizer() |
1 2 3 4 5 6 7 8 |
func setupImageView() { panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.panGestureAction(_:))) . . . . . } |
1 2 3 4 5 6 |
@objc func panGestureAction(_ recognizer: UIPanGestureRecognizer){ self.view.bringSubviewToFront(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) } |
1 2 3 4 5 |
override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .green setupViews() } |
Conclusion
I hope this blog will help you in understanding the behaviour of pan gestures, if you have any comments, questions, or recommendations, feel free to post them in the comment section below!
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.