I want to navigate between my tab bar using swipe gestures. What is the easiest way to do that? I tried something like this...
import UIKit
class postAdViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
view.addGestureRecognizer(leftSwipe)
}
func handleSwipes(sender:UISwipeGestureRecognizer) {
if (sender.direction == .left) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "favourireviewcontroller") as! UIViewController
self.present(vc, animated: true, completion: nil)
}
if (sender.direction == .right) {
}
}
If I try to swipe right nothing happens. The app crashes when swiping left the following error message
unrecognized selector sent to instance 0x7f924380a730
Well if you want to navigate through you tabBar
you should implement a swipeGestureRecognizer
for .left
and .right
and then work with the tabBarController?.selectedIndex
, something like this:
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
swipeRight.direction = UISwipeGestureRecognizerDirection.right
self.view.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
swipeLeft.direction = UISwipeGestureRecognizerDirection.left
self.view.addGestureRecognizer(swipeLeft)
func swiped(_ gesture: UISwipeGestureRecognizer) {
if gesture.direction == .left {
if (self.tabBarController?.selectedIndex)! < 2 { // set your total tabs here
self.tabBarController?.selectedIndex += 1
}
} else if gesture.direction == .right {
if (self.tabBarController?.selectedIndex)! > 0 {
self.tabBarController?.selectedIndex -= 1
}
}
}
Here's a Swift4 example of swiping left and right right through a TabBar controller.
Things I don't like about this solution: - seems like you should be able to register the handler once and distinguish the direction within the handler itself but I wasn't able to easily do that. - I'm also curious how to do a gesture that includes a drag for visual effect. I'm think I need to include a PanGesture as well in order to pull that off.
override func viewDidLoad() {
super.viewDidLoad()
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(_:)))
let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(_:)))
leftSwipe.direction = .left
rightSwipe.direction = .right
self.view.addGestureRecognizer(leftSwipe)
self.view.addGestureRecognizer(rightSwipe)
}
And then the handler:
@objc func handleSwipes(_ sender:UISwipeGestureRecognizer) {
if sender.direction == .left {
self.tabBarController!.selectedIndex += 1
}
if sender.direction == .right {
self.tabBarController!.selectedIndex -= 1
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With