[Swift]: Add Swipe Gestures

swift

05/06/2019


Adding swipe gestures in Swift 5

If you'd like to add a swipe left gesture

SWIFT
override func viewDidLoad() {
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeGesture))
swipeLeft.direction = UISwipeGestureRecognizer.Direction.left
self.view.addGestureRecognizer(swipeLeft)
}
@objc
func swipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
if swipeGesture.direction == UISwipeGestureRecognizer.Direction.left {
print("left swipe") ///
}
}
}

Similarly, you can add more cases for other directions

SWIFT
@objc
func swipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizer.Direction.right:
print("right swipe") ///
case UISwipeGestureRecognizer.Direction.down:
print("down swipe") ///
case UISwipeGestureRecognizer.Direction.left:
print("left swipe") ///
case UISwipeGestureRecognizer.Direction.up:
print("up swipe") ///
default:
break
}
}
}

WRITTEN BY

Keeping a record