Swift: move UIView on slide gesture Swift: move UIView on slide gesture ios ios

Swift: move UIView on slide gesture


Finally did it like below.

let gesture = UIPanGestureRecognizer(target: self, action: Selector("wasDragged:"))slideUpView.addGestureRecognizer(gesture)slideUpView.userInteractionEnabled = truegesture.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)    }}


You probably want to use a UIPanGestureRecognizer.

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

And to drag the object only along the y-axis:

func wasDragged(gesture: UIPanGestureRecognizer) {    let translation = gesture.translationInView(self.view)    // Use translation.y to change the position of your customView, e.g.    customView.center.y = translation.y // Customize this.}


Swift 4:

@objc func wasDragged(_ gestureRecognizer: UIPanGestureRecognizer) {    if gestureRecognizer.state == UIGestureRecognizer.State.began || gestureRecognizer.state == UIGestureRecognizer.State.changed {        let translation = gestureRecognizer.translation(in: self.view)        print(gestureRecognizer.view!.center.y)        if(gestureRecognizer.view!.center.y < 555) {            gestureRecognizer.view!.center = CGPoint(x: gestureRecognizer.view!.center.x, y: gestureRecognizer.view!.center.y + translation.y)        }else {            gestureRecognizer.view!.center = CGPoint(x:gestureRecognizer.view!.center.x, y:554)        }        gestureRecognizer.setTranslation(CGPoint(x: 0, y: 0), in: self.view)    }}

Call

let gesture = UIPanGestureRecognizer(target: self, action: self.wasDragged(gestureRecognizer:))customView.addGestureRecognizer(gesture)gesture.delegate = self


matomo