Swift 3.0.1(及以下版本)的问题在于,即使 UISwipeGestureRecognizerDirection符合 OptionSet,下面的代码片段也会编译,但不会产生任何积极的预期结果:
// This compiles but does not work
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(gestureHandler))
gesture.direction = [.right, .left, .up, .down]
self.addGestureRecognizer(gesture)
[UISwipeGestureRecognizerDirection.right,
UISwipeGestureRecognizerDirection.left,
UISwipeGestureRecognizerDirection.up,
UISwipeGestureRecognizerDirection.down].forEach({ direction in
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipe.direction = direction
self.view.addGestureRecognizer(swipe)
})
func willMoveFromView(view: UIView) {
if view.gestureRecognizers != nil {
for gesture in view.gestureRecognizers! {
//view.removeGestureRecognizer(gesture)//This will remove all gestures including tap etc...
if let recognizer = gesture as? UISwipeGestureRecognizer {
//view.removeGestureRecognizer(recognizer)//This will remove all swipe gestures
if recognizer.direction == .left {//Especially for left swipe
view.removeGestureRecognizer(recognizer)
}
}
}
}
}
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
swipeRight.direction = .right
self.view.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
swipeLeft.direction = .left
self.view.addGestureRecognizer(swipeLeft)
}
// Example Tabbar 5 pages
@objc func swiped(_ gesture: UISwipeGestureRecognizer) {
if gesture.direction == .left {
if (self.tabBarController?.selectedIndex)! < 5 {
self.tabBarController?.selectedIndex += 1
}
} else if gesture.direction == .right {
if (self.tabBarController?.selectedIndex)! > 0 {
self.tabBarController?.selectedIndex -= 1
}
}
}
}
使用这个 baseController类:
class YourViewController: BaseViewController {
// its done. Swipe successful
//Now you can use all the Controller you have created without writing any code.
}