Search code examples
iosswiftxcodeuitabbargesture

How can I switch tab bar tabs using left and right swipe gestures?


I have a UITabBarController with two tabs connected to it. How can I use left and right swipe gestures in the two views to switch tabs left and right?

I've seen other questions similar to this but all of them use Objective-C. Also, if this can be all done in the storyboard, I'd prefer that over having to use Swift code.


Solution

  • Add following swipe gestures to your viewcontroller view

     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)
    // below code create swipe gestures function
    // MARK: - swiped
    @objc  func swiped(_ gesture: UISwipeGestureRecognizer) {
    if gesture.direction == .left {
        if (self.tabBarController?.selectedIndex)! < 2
        { // set here  your total tabs
            self.tabBarController?.selectedIndex += 1
        }
    } else if gesture.direction == .right {
        if (self.tabBarController?.selectedIndex)! > 0 {
            self.tabBarController?.selectedIndex -= 1
        }
    }
    }