简体   繁体   中英

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.

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
    }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM