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.
Example of Pan Gestures in Swift- Dragging ImageView
- First, create the Xcode project and save it.
- Now add the image as a subview in the view of ViewController.
1let imageView = UIImageView()12345678910111213func setupImageView() {imageView.isUserInteractionEnabled = trueimageView.addGestureRecognizer(panGesture)imageView.translatesAutoresizingMaskIntoConstraints = falseimageView.image = UIImage(named: "mobikul")imageView.contentMode = .scaleAspectFillimageView.clipsToBounds = trueview.addSubview(imageView)imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = trueimageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = trueimageView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.4).isActive = trueimageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: 1).isActive = true}
- Add image in the Assets.xcassets.
- Now add the pan gesture in the ViewController.
1var panGesture = UIPanGestureRecognizer()12345678func setupImageView() {panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.panGestureAction(_:))).....}
- Add the selector or action for the pan gesture as:
123456@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)}12345override func viewDidLoad() {super.viewDidLoad()view.backgroundColor = .greensetupViews()}
- Now run the app and it works as:
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!