检测以编程方式设置的UITabBar选定索引/项目更改

Jay*_*iyk 15 uitabbarcontroller uitabbaritem uitabbar ios

我想知道 以编程方式完成更改,我们如何检测选定的TabBar项目或索引何时更改

self.tabBarController.selectedIndex = 1;
Run Code Online (Sandbox Code Playgroud)

这两个委托函数仅在用户选择tabBar项时检测更改.当以编程方式完成对selectedIndex的更改时,它不会触发.

func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
    println("tabBarController didSelectViewController")
}

override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem!) {
    println("tabBar didSelectItem")
}
Run Code Online (Sandbox Code Playgroud)

Edd*_*Liu 17

以前的答案足以"检测"更改,但是它不会检测正在按下哪个索引.

func selectItemWithIndex(value: Int) {
    self.tabBarControllertabBarController.selectedIndex = value;
    self.tabBar(self.tabBar, didSelectItem: (self.tabBar.items as! [UITabBarItem])[value]);
}
Run Code Online (Sandbox Code Playgroud)

self.selectedIndex不会立即返回选定的索引.要检查正在按下哪个项目,我们需要将项目与UITabBarController中的tabBarItems进行比较

override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem!) {
    if item == (self.tabBar.items as! [UITabBarItem])[0]{ 
       //Do something if index is 0
    }
    else if item == (self.tabBar.items as! [UITabBarItem])[1]{
       //Do something if index is 1
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我不确定直接调用委托方法是一个好习惯,因为它的目的是自动触发。 (2认同)

Mes*_*ery 8

在这里的所有答案中,如果您UITabBarController已经进行了子类化,这里是所有标签栏更改的简单解决方案(用户启动和编程):

// Override selectedViewController for User initiated changes
override var selectedViewController: UIViewController? {
    didSet {
        tabChangedTo(selectedIndex: selectedIndex)
    }
}
// Override selectedIndex for Programmatic changes    
override var selectedIndex: Int {
    didSet {
        tabChangedTo(selectedIndex: selectedIndex)
    }
}

// handle new selection
 func tabChangedTo(selectedIndex: Int) {}
Run Code Online (Sandbox Code Playgroud)

  • 男人!你救了我的工作!非常感谢!它解决了我为每个选项卡显示初始 vc 的最大问题:) (2认同)

Vin*_*kar 5

selectedIndex在 swift 中,您可以通过重写的属性来做到这一点UITabBarController

首先子类化UITabBarController并添加以下所有代码。

//Overriding this to get callback whenever its value is changes
   override var selectedIndex: Int {
      didSet {
         handleTabSelection(selectedIndex: selectedIndex)
      }
   }
Run Code Online (Sandbox Code Playgroud)

还添加这个委托方法UITabBarControllerDelegate

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
    //Tab tapped
    guard let viewControllers = tabBarController.viewControllers else { return }
    let tappedIndex = viewControllers.index(of: viewController)! 
    //Tab tapped at tappedIndex
    handleTabSelection(selectedIndex: tappedIndex)
}
Run Code Online (Sandbox Code Playgroud)

最后,我们从两个地方调用这个方法,以便处理所有情况。

private func handleTabSelection(selectedIndex: Int) {
    //Do something on tab selection at selectedIndex
}
Run Code Online (Sandbox Code Playgroud)