Search code examples
swiftuiscrollviewuipangesturerecognizer

Dragging a uiview in a scrollview


I have a scroll view that contains an Image View. I add some UIview to that image that I want to drag and drop them in the image area.

I Already use UIPanGestureRecognizer (Draggable UIView Swift 3) but it doesn't work.

@IBOutlet weak var mapImage: UIImageView!
@IBOutlet weak var scrollView: UIScrollView!
 override func viewDidLoad() {
        let viewDemo = UIView()
        scrollView.minimumZoomScale = 1.0
        scrollView.maximumZoomScale = 6.0
        let panGesture = UIPanGestureRecognizer(target: self, action: 
        #selector(moveObject(_:)))
        viewDemo.frame = CGRect(x: 50, y: 50, width: 40, height: 40)
        viewDemo.backgroundColor = .red
        viewDemo.layer.cornerRadius = 20
        viewDemo.isUserInteractionEnabled = true
        viewDemo.addGestureRecognizer(panGesture)
        mapImage.addSubview(viewDemo)

}
   @objc func moveObject(_ gesture: UIPanGestureRecognizer){

        //1. Check That We Have A Valid Draggable View
        guard let draggedObject = gesture.view else { return }

        if gesture.state == .began || gesture.state == .changed {

            //2. Set The Translation & Move The View
            let translation = gesture.translation(in: self.view)
            draggedObject.center = CGPoint(x: draggedObject.center.x + translation.x, y: draggedObject.center.y + translation.y)
            gesture.setTranslation(CGPoint.zero, in: self.view)


        }else if gesture.state == .ended {

        }
    }

The moveObject doesn’t execute when I drag and drop the UIview. I Already tried to Disable scrolling the scroll view with scrollView?.isScrollEnabled = false


Solution

  • You have to enable user interaction of your UIImageView.

    mapImage.isUserInteractionEnabled = true