【问题标题】:UITabBar delegate method not being called (Programatically created UI)未调用 UITabBar 委托方法(以编程方式创建的 UI)
【发布时间】:2020-07-01 02:02:12
【问题描述】:

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

【问题讨论】:

  • 我不确定UITabBar 是否打算在没有UITabBarController 的情况下工作。如果您不打算使用控制器,为什么不使用代表选项卡的按钮制作自定义视图?看起来你只是想用它来接收点击事件,但这不是它的设计目的。只需改用UIButton

标签: ios swift storyboard uitabbarcontroller uitabbar


【解决方案1】:

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

    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]

【讨论】:

    【解决方案2】:

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

    真正造成麻烦的是一些超级UIViews,我在其中添加了所有其他视图,包括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!)
    

    之后一切正常。 所以这个方法其实是有功能的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      相关资源
      最近更新 更多