zacreme
zacreme

Reputation: 169

Detect if user is moving finger left or right (Swift)

This is not Sprite Kit.

If I have a variable like the one below

var value = 0

How am I able to increase the value if the user drags right and decrease if they drag left?

Thanks!

Upvotes: 0

Views: 839

Answers (2)

Jinhyung Park
Jinhyung Park

Reputation: 471

Like Caleb commented, Ray's tutorial is great, but if you want the actual swift example, please check the next example:

class ViewController: UIViewController, UIGestureRecognizerDelegate {

    private var value: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.blackColor()

        let recognizer = UIPanGestureRecognizer(target: self, action: Selector("handleDragging:"))

        let inputView = UIView(frame: CGRectMake(0, 0, 100, 100))
        inputView.backgroundColor = UIColor.whiteColor()
        inputView.userInteractionEnabled = true
        inputView.addGestureRecognizer(recognizer)

        self.view.addSubview(inputView)
    }

    func handleDragging(recognizer: UIPanGestureRecognizer) {
        if (recognizer.state == .Changed) {
            let point = recognizer.velocityInView(recognizer.view?.superview)
            if (point.x > 0) {
                self.value++;
            } else {
                self.value--;
            }
            println(self.value)
        }
    }
}

Upvotes: 1

Chris Slowik
Chris Slowik

Reputation: 2879

You can use the velocityInView method of UIPanGestureRecognizer to determine which direction you're going. It returns a CGPoint, so you can pull out the x and y values as you wish. Positive is right/down, negative is left/up.

Upvotes: 0

Related Questions