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

问题描述 投票:0回答:2

我在开发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

ios swift storyboard uitabbarcontroller uitabbar
2个回答
0
投票

请确保具有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]

0
投票

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

实际上引起麻烦的是一些超级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!)

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

© www.soinside.com 2019 - 2024. All rights reserved.