簡體   English   中英

在 Swift 更改 UITabBar selectedItem

[英]Change UITabBar selectedItem in Swift

如何以編程方式更改 UITabBar 中的選定項?

Swift 3及更高版本

從Swift 3開始,您也可以使用

tabBarController.selectedIndex = 0 // (or any other existing index)

(謝謝你,@ nidomiro。)


Swift 2.2及更早版本

請嘗試以下方法

tabBar.selectedItem = tabBar.items![newIndex] as! UITabBarItem

假設你有機會獲得UITabBarController擁有該UITabBar ,你可以做以下

self.selectedViewController = self.viewControllers![newIndex] as! UIViewController

上面的代碼行應該放在UITabBarController子類的內部。

但是,如果您可以從“外部”訪問標簽欄控制器,請執行以下操作

tabBarController.selectedViewController = tabBarController.viewControllers![newIndex] as! UIViewController

Swift 5 及更高版本

class YOUR_TABBAR_CONTROLLER: UITabBarController {    

  override func viewDidLoad() {
  super.viewDidLoad()

  self.selectedIndex = 0 (or any other existing index)

  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM