Search code examples
iosswiftuiviewuigesturerecognizeruitouch

How to make a view follow my finger to move? Direction is from left to right


I want to implement a function similar to a slider. For example, the button follows the finger and moves from left to right. Like this: enter image description here

Should I use UISwipeGestureRecognizer. Or UIPanGestureRecognizer? I used a swipe gesture but I don't know how to update the frame.

var swipeRight = UISwipeGestureRecognizer(target: self, action: 
#selector(self.respondToSwipeGesture(sender:)))
swipeView.isUserInteractionEnabled = true
swipeView.addGestureRecognizer(swipeRight)

Solution

  • You can add the pan gesture to the view you want to drag. The method for drag looks like this:

    func draggedView(_ sender: UIPanGestureRecognizer) {
        let translation = sender.translation(in: self.view)
        draggableView.center = CGPoint(x: draggableView.center.x + translation.x, y: 
        draggableView.center.y)
        sender.setTranslation(CGPoint.zero, in: self.view)
    }
    

    You can use translation x or y depending if you want to move the view horizontally or vertically, or both.