I want to use a swipe gesture to navigate between tab bar controllers while keep the default tab bars. I used this code but shows an error.
import UIKit
class FirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
leftSwipe.direction = .Left
view.addGestureRecognizer(leftSwipe)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
func handleSwipes(sender:UISwipeGestureRecognizer) {
if (sender.direction == .Left) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as! UIViewController
self.presentViewController(vc, animated: false, completion: nil)
}
if (sender.direction == .Right) {
}
}
}
}
Your function handleSwipes
must be a class level function, not an inner function of another function:
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
// remove the func from here
}
func handleSwipes(sender:UISwipeGestureRecognizer) {
if (sender.direction == .Left) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as! UIViewController
self.presentViewController(vc, animated: false, completion: nil)
}
if (sender.direction == .Right) {
}
}
That is the obvious error I can see. You should always post your error message with your questions to improve the quality of answers.
I could get your code working by adding the ID to the SecondViewController class as shown in the image below :
The only problem is, after getting this to work, you won't be able to see the Tab bar controller, since you have opened the SecondViewController which doesn't have the UI Tab bar controller.
Please let me know if my solution works and did you find any other way of swiping to second view and having the UI tab bar in place as well.
[EDIT] Actually I dug down a bit more and found out it was easier than I expected. The fix to our problem of tabBar controller not showing up is as follows :
func handleSwipes(sender:UISwipeGestureRecognizer) {
let selectedIndex: Int = self.tabBarController!.selectedIndex
self.tabBarController!.selectedIndex = selectedIndex + 1
}
The best way for UITabBarViewController (Swift 3.0) will be next:
func handleSwipes(sender:UISwipeGestureRecognizer) {
if sender.direction == UISwipeGestureRecognizerDirection.left {
self.selectedIndex += 1
} else if sender.direction == UISwipeGestureRecognizerDirection.right {
self.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