iOS Gestures in Swift – How to


iOS Gestures in Swift

iOS gestures can be useful in your app. And here is a short demonstration on how to implement iOS gestures in your app.

It seems like iOS gestures require one recogniser for each direction.


//Recogniser
let swipeRight = UISwipeGestureRecognizer(target: self, action: "respond:")
swipeRight.direction = .Right
view.addGestureRecognizer(swipeRight)

respond is the name of the handler or function to run the code. So anything you want happening when your user is swiping goes into that function. Like this, just an example to change the text in a label.


// Respond function
func respond(gesture: UIGestureRecognizer) {
lblDirection.text = "Right"
}

If you add recognisers for all four direction, you can still point all recogniser to the same function. And use something like this to check for what direction the user swiped.


// Respond function with all four directions
func respond(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Right:
lblDirection.text = "Right"
case UISwipeGestureRecognizerDirection.Left:
lblDirection.text = "Left"
case UISwipeGestureRecognizerDirection.Up:
lblDirection.text = "Up"
case UISwipeGestureRecognizerDirection.Down:
lblDirection.text = "Down"
default:
break
}
}
}

That is how you implant iOS gestures. You can also download a working app with this code from github using this link: https://github.com/solron/Swipe-Gesture

If you want to see in a video how to do this. You can check out my video here on youtube.https://www.youtube.com/watch?v=EzBnQg6ZKrs

Thats it really!

Happy coding!

Have any Question or Comment?

Leave a Reply