Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change UITabBar selectedItem in Swift

How can I programmatically change the selected item in a UITabBar?

like image 227
Zia Avatar asked Jul 09 '15 22:07

Zia


People also ask

How do I change font size in Tabbar in Swift?

I know that this is how you change it in Objective-C: [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"AmericanTypewriter" size:20. 0f], UITextAttributeFont, nil] forState:UIControlStateNormal];

How do I change the tab title color in Swift bar?

backgroundColor = UIColor(red:1, green:0, blue:0, alpha:1) / UITabBar. appearance(). tintColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1) // New!! func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {...}


2 Answers

Swift 3 and later

As of Swift 3, you can also use

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

(Thank you, @nidomiro.)


Swift 2.2 and earlier

Try the following

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

Assuming you have access to the UITabBarController that owns the UITabBar, you can do the following

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

The above line of code should be put somewhere inside of the UITabBarController subclass.

But if you have access to the tab bar controller from "outside," do the following

tabBarController.selectedViewController = tabBarController.viewControllers![newIndex] as! UIViewController
like image 133
ndmeiri Avatar answered Oct 21 '22 00:10

ndmeiri


Swift 5 and Later

class YOUR_TABBAR_CONTROLLER: UITabBarController {    

  override func viewDidLoad() {
  super.viewDidLoad()

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

  }
}
like image 37
asilturk Avatar answered Oct 20 '22 23:10

asilturk