问题
I am using Swift 3
and I researched various methods to set the backgroundColor
color of a UITabBar
. The most simple method was to change the property in the didFinishLaunchingWithOptions
of the AppDelegate
. When I tried to do this, the UITabBar
launches with the standard color, which is not my intended result.
However, when I go to the next tab, the UITabBar
color gets changed to my intended color.
Following this, I tried to subclass
my UITabBarController
and I tried to set the background colors in both the viewDidLoad
and in the viewDidLayoutSubViews
. All three of these attempts exhibited the exact same behavior - which was the UITabBar
launched with the standard color, and only changed colors when I tabbed to the next tab.
Here is my code:
App Delegate
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)
-> Bool {
UITabBar.appearance().backgroundColor = UIColor.red
return true
}
viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
self.tabBar.backgroundColor = UIColor.red
}
viewDidLayoutSubviews
override func viewDidLayoutSubviews() {
self.tabBar.backgroundColor = UIColor.red
}
My questions are the following:
1) Can I eliminate this as being a constraint issue? I didn't modify or set any constraints for the UITabBar
2) I have a launch screen where the user selects acknowledges something and then they are segued
to the UITabBarController
. Could this be part of the issue?
回答1:
The basic way to change to a tab bar's color is not to set its backgroundColor
as you are doing, but rather to set its barTintColor
. (For more sophisticated control, use a colored backgroundImage
.)
回答2:
Putting this in my app delegate gets me a tab bar that's tinted red.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let tabBarVC = UITabBarController()
tabBarVC.viewControllers = [FirstViewController(), SecondViewController()]
tabBarVC.tabBar.backgroundColor = UIColor.red
window?.rootViewController = tabBarVC
window?.makeKeyAndVisible()
return true
}
来源:https://stackoverflow.com/questions/41052346/odd-behavior-from-uitabbar-where-background-color-only-shows-for-one-tab