TabController disappears when using swipe gesture

200 Views Asked by At

I have an app with a 3 tabs. I want to swipe right or left to go to another tab.

My code:

//Swipe Between Tabs
    let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
    let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
    rightSwipe.direction = .Right
    leftSwipe.direction = .Left
    view.addGestureRecognizer(rightSwipe)
    view.addGestureRecognizer(leftSwipe)
    //end Swipe

and the function to carry it out is

func handleSwipes(sender:UISwipeGestureRecognizer) {
    if (sender.direction == .Left) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("PantryList")
        let navigationController = UINavigationController(rootViewController: vc)

        self.presentViewController(navigationController, animated: true, completion: nil)
    }
    if (sender.direction == .Right) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("ToDoList")
        let navigationController = UINavigationController(rootViewController: vc)

        self.presentViewController(navigationController, animated: true, completion: nil)
    }
}

My problem is that tabBarController at the bottom disappears when swipe is used. From what I have found it has to do with the "presentViewController" method. Is this what is causing it and is there a way to do it without losing the tabBarController? I really don't want to use prepareForSegueWithIdentifier if I don't have to. That seems like more work than needs to be done unless that's how it has to be done.

3

There are 3 best solutions below

1
On BEST ANSWER
if (sender.direction == .Right) {
    self.navigationController.tabBarController.selectedIndex = 1
}
0
On

I too think your problem is with the presentViewController:. Assuming the swipe handling code is in the UITabBarController, what you are doing here is pushing a VC on top of the whole tabcontroller.

I'll try to move the selected view controller's view along the next VC view to be displayed (in the direction given by the swipe move), then change the value of the UITabBarController selectedViewController to your new VC.

0
On

Of course it's because you are presenting view controller on top of current view controller. To switch between UITabbarController viewControllers, you can use setSelectedIndex: method, in your case, your first vc will have 0 index, second and third 1 and 2 respectively. Just switch the selected index on swipe, and you are done! Good luck!