简体   繁体   中英

Swift 2.2 How to change background color of tab bar controller

I've been trying to change the background of the tab bar, and have read many posts here in ObjC, many of them quite old. But I didn't find any for Swift, which is what I'm using.

I finally figured out how to do it from code, so the tab bar colors can be changed with each theme color change. Here are the references that I used:

  override func viewWillAppear(animated: Bool) {
    // set tab bar background color, including the More tab
    self.tabBarController?.tabBar.backgroundColor = UIColor.blueColor()
  }

I put this code in the view controller for the first tab that appears when the app starts up, so that it gets run "first." It works fine as far as I can tell, even when I have 8 tabs and use the More... tab.

And I bound the same code to buttons in various tabs, so I can change the tab bar color from anywhere in my code.

But I confess that as a newbie, I'm not sure that's the best location to change the tab bar color. If this is the wrong place, please correct me.

I post this code here since it would have saved me a few hours, and I hope that it can save someone else some (swift) time.

This is a fine way to change the color of a UITabBar . If you want to avoid setting the color in every viewController that is embedded inside of your UITabBarController , you could also create a subclass of UITabBarController and set it there. This way no matter what page comes up first, the color will be set.

To create a subclass of UITabBarController , just go to file > new > file > cocoa touch class...Then setup your file like in this photo

添加文件

Now in your storyboard, set the custom class on your tabBarController

故事板

Finally, in your file you created MyTabBarController (or whatever you called it):

class MyTabBarController: UITabBarController {

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    self.tabBar.barTintColor = .blueColor()
}
...

Xcode 9

Storyboard

It possible to set background color directly in view controller (currently in TabBarViewController), for this you need to define Key Path . Don't forget to remove background color on nested view, otherwise it will overlap superview's background color.

在此输入图像描述

You can change like this

tabBarController.tabBar.barTintColor = [UIColor blackColor];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM