Swift: move UIView on slide gesture

Nagendra Rao picture Nagendra Rao · Feb 5, 2016 · Viewed 28.1k times · Source

I am trying to move a UIView on slide up gesture from its initial position to a fixed final position. The image should move with the hand gesture, and not animate independently.

I haven't tried anything as I have no clue where to start, which gesture class to use.

enter image description here

Answer

Nagendra Rao picture Nagendra Rao · Mar 18, 2016

Finally did it like below.

let gesture = UIPanGestureRecognizer(target: self, action: Selector("wasDragged:"))
slideUpView.addGestureRecognizer(gesture)
slideUpView.userInteractionEnabled = true
gesture.delegate = self

The following function is called when the gesture is detected, (here I am restricting the view to have a maximum centre.y of 555, & I'm resetting back to 554 when the view moves past this point)

func wasDragged(gestureRecognizer: UIPanGestureRecognizer) {
    if gestureRecognizer.state == UIGestureRecognizerState.Began || gestureRecognizer.state == UIGestureRecognizerState.Changed {
        let translation = gestureRecognizer.translationInView(self.view)
        print(gestureRecognizer.view!.center.y)
        if(gestureRecognizer.view!.center.y < 555) {
            gestureRecognizer.view!.center = CGPointMake(gestureRecognizer.view!.center.x, gestureRecognizer.view!.center.y + translation.y)
        }else {
            gestureRecognizer.view!.center = CGPointMake(gestureRecognizer.view!.center.x, 554)
        }

        gestureRecognizer.setTranslation(CGPointMake(0,0), inView: self.view)
    }

}