Search code examples
iosswiftstoryboarduitabbarcontrolleruitabbar

UITabBar delegate method not being called (Programatically created UI)


I'm somewhat new at developing iOS applications, I'm creating an app but I'm not using any storyboards.

I want to use a UITabBar, but when I click (or tap) any item of the bar, the delegate didSelect method is not being called.

I don't know what I am doing wrong, this is my code:

class MainMenuVC: BaseVC, UITabBarDelegate {

  var tabBarMenu : UITabBar?

  override func viewDidLoad() {
      super.viewDidLoad()

      self.tabBarMenu = UITabBar.init()
      self.tabBarMenu?.delegate = self;

      tabBarMenu!.items = barItems // I omitted the code to populate this array on purpose

      // Tab Style
      tabBarMenu!.backgroundColor = Constants.Colors.gray
      tabBarMenu!.tintColor = Constants.Colors.gray
      tabBarMenu!.barTintColor = Constants.Colors.gray
      tabBarMenu!.isTranslucent = false
      tabBarMenu!.isUserInteractionEnabled = true

      //Tab bar position
      tabBarMenu!.frame = CGRect(x: contentView.frame.origin.x, y: contentView.frame.size.height - Constants.Dimensions.tabBarHeight, width: contentView.frame.size.width, height: Constants.Dimensions.tabBarHeight)

      // Adding
      self.view.addSubview(tabBarMenu!)
      self.view.bringSubviewToFront(tabBarMenu!)
  }

  // This is not being called
  func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
      self.handleTabBarTab(tag: item.tag)
  }
}

My BaseVC is a regular UIViewController, I'm not using UITabBarViewController


Solution

  • The code I posted here is a bit different from the code I'm actually working on.

    What was actually causing trouble were some super UIViews where I was adding all the other views, including the UITabBar. These views were not enabled to user interaction.

    So all I did was:

    // Enabled the main view container to user interaction
    // This was actually causing the issue
    self.containerView.isUserInteractionEnabled = true
    
    // Adding the views
    self.containerView.addSubview(tabBarMenu!)
    self.containerView.bringSubviewToFront(tabBarMenu!)
    

    Everything worked good after that. So this approach is actually functional