Search code examples
iosswiftuitabbar

No touch gestures were set, but tabBar only responds to long press. Why?


I have a view which has a tabBar at the top, and below it is a tableView. The tableView has touch gestures which are constrained to it (tap, double tap, and pan gesture). However, the tabBar has no touch gestures installed but only responds to a long press touch.

Some useful information: - tabBar delegate was set to self

only tabBar code:

func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    if item.tag == 101 { //tag number of first tab bar item
        print("tableView")
    }
    if item.tag == 102 { //tag number of second tab bar item
        print("collectionView") //going to add collection view eventually
    }
}

any help will be appreciated. Thanks!


Solution

  • Since I couldn't figure it out (it probably has something to do with the tableView content underneath it), I decided to go with a workaround using a touch gesture:

    @IBOutlet weak var tabBar: UITabBar!
    
    override func viewDidLoad() {
        let tabBarTap = UITapGestureRecognizer(target: self, action: #selector(MyViewController.switchSelectedTabItem(tapGestureRecognizer:)))
        tabBarTap.delegate = self
        tabBarTap.numberOfTapsRequired = 1
        tabBarTap.numberOfTouchesRequired = 1
        tabBar.addGestureRecognizer(tabBarTap)
    }
    
    @objc func switchSelectedTabItem(tapGestureRecognizer: UITapGestureRecognizer) {
        let touchPoint = tapGestureRecognizer.location(in: self.view)
        let split = tabBar.frame.width/2    //because i have two tab bar items. divide it by how many tab bar items you have
        if touchPoint.x > split {           //again, since i have two tab bar items, i can just divide the location of the tap into two sections (tab bar item 1 and tab bar item 2)
            tabBar.selectedItem = tabBar.items?[1]
            //run code for when second item is selected
        } else {
            tabBar.selectedItem = tabBar.items?[0]
            //run code for when second item is selected
        }
    }