UISwipeGestureRecognizer
has a direction
property that has the following definition:
var direction: UISwipeGestureRecognizerDirection
The permitted direction of the swipe for this gesture recognizer.
The problem with Swift 3.0.1 (and below) is that even if UISwipeGestureRecognizerDirection
conforms to OptionSet
, the following snippet will compile but won't produce any positive expected result:
// This compiles but does not work
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(gestureHandler))
gesture.direction = [.right, .left, .up, .down]
self.addGestureRecognizer(gesture)
As a workaround, you will have to create a UISwipeGestureRecognizer
for each desired direction
.
The following Playground code shows how to implement several UISwipeGestureRecognizer
for the same UIView
and the same selector
using Array's map
method:
import UIKit
import PlaygroundSupport
class SwipeableView: UIView {
convenience init() {
self.init(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
backgroundColor = .red
[UISwipeGestureRecognizerDirection.right, .left, .up, .down].map({
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(gestureHandler))
gesture.direction = $0
self.addGestureRecognizer(gesture)
})
}
func gestureHandler(sender: UISwipeGestureRecognizer) {
switch sender.direction {
case [.left]: frame.origin.x -= 10
case [.right]: frame.origin.x += 10
case [.up]: frame.origin.y -= 10
case [.down]: frame.origin.y += 10
default: break
}
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(SwipeableView())
}
}
let controller = ViewController()
PlaygroundPage.current.liveView = controller