UI未调用 TabBar 委托方法(以编程方式创建 UI)

UITabBar delegate method not being called (Programatically created UI)

我在开发 iOS 应用程序方面有些陌生,我正在创建一个应用程序,但我没有使用任何故事板。

我想使用 UITabBar,但是当我单击(或点击)栏的任何项目时,委托 didSelect 方法没有被调用。

我不知道我做错了什么,这是我的代码:

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

我的 BaseVC 是普通 UIViewController,我没有使用 UITabBarViewController

确保有一个 UITabBarItem 的 TAG,这对我来说很好用:

    self.tabBarMenu = UITabBar(frame: CGRect(x: contentView.frame.origin.x, y: contentView.frame.size.height - Constants.Dimensions.tabBarHeight, width: contentView.frame.size.width, height: Constants.Dimensions.tabBarHeight))
    self.tabBarMenu?.delegate = self

    let tabOneBarItem = UITabBarItem(title: "Test", image: nil, tag: 1)
    let tabTwoBarItem = UITabBarItem(title: "Test2", image: nil, tag: 2)

    tabBarMenu!.items = [tabOneBarItem, tabTwoBarItem]

我在此处发布的代码与我实际使用的代码有些不同。

真正造成麻烦的是一些超级 UIView,我在其中添加了所有其他视图,包括 UITabBar。这些视图未启用用户交互。

所以我所做的就是:

// 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!)

之后一切正常。 所以这种方法实际上是有效的