如何确定性地设置UITabBar的背景颜色和着色颜色

35

我一直在尝试设置UITabBar的色调和背景颜色,但是好像什么都不起作用。 到目前为止我尝试过:

tabBarController?.tabBar.backgroundColor = UIColor.orangeColor()
tabBarController?.tabBar.barTintColor = UIColor.whiteColor()

以及:

UITabBar.appearance().tintColor = UIColor.orangeColor()

这两个似乎对我的选项卡栏没有任何影响。我还想提到,我已经将 VC 嵌入一个导航控制器中,全局色调颜色设置正常工作。

6个回答

59

如果您想隐式设置选项卡栏的 tint 和 barTint 颜色,则需要在您的 Appdelegate.swift 中进行设置。

    UITabBar.appearance().barTintColor = .orange
    UITabBar.appearance().tintColor = .green

如果您想为特定的视图控制器设置tabbar的tint和barTint颜色,那么在ViewController.swift文件中,

 self.tabBarController?.tabBar.tintColor = .orange
 self.tabBarController?.tabBar.barTintColor = .green

2
嗨@Lion,UITabBar.appearance().barTintColor中不存在barTintColor吗? - Twitter khuong291
@Khuong 我可以通过访问实例来获取它,但是我无法通过appearance()类来实现。 - Adrian
2
@Khuong 它确实存在,只是 Xcode 完全拒绝在自动完成选项中显示它。 - SomaMan
Swift 4: UITabBar.appearance().barTintColor = UIColor.orange UITabBar.appearance().tintColor = UIColor.green - ingconti
UITabBar.appearance().backgroundColor = UIColor.green 似乎完全没有任何作用。barTint可以接近,但绝对不是同样的效果。这是预期的吗? - user5306470
显示剩余2条评论

22

使用 barTintColor 属性设置选项卡栏的背景颜色:

self.tabBar.barTintColor = UIColor.blueColor()
//or
UITabBar.appearance().barTintColor = UIColor.blueColor()

对于选项卡栏色调颜色:

self.tabBar.tintColor = UIColor.whiteColor() // Selected tab color
//or
UITabBar.appearance().tintColor = UIColor.whiteColor()

输入图像描述


我的 tabBar 长这样,但是当用户点击任何选项卡时,该选项将被禁用。但是颜色也会改变,我该如何改变它呢?这是我的问题链接:https://dev59.com/LaPia4cB1Zd3GeqP5uh1#45439032?noredirect=1 - Saeed Rahmatolahi
颜色接近但不完全相同。尝试将视图背景设置为相同的颜色,亲自查看。 - user5306470
+1 说明“tintColor”和“barTintColor”的区别。苹果公司可能还能想出更加晦涩难懂、毫无帮助的属性名称吗? - Echelon

2

与iOS 15中,当UINavigationBar后面没有内容时默认是透明的类似,UITabBar也是同样的方式。这可能会带来一个免费的视觉更新(因为在使用Xcode 13构建时默认已启用),或者可能会给您的应用程序带来很多问题。

if #available(iOS 13.0, *) { 
    let tabBarAppearance: UITabBarAppearance = UITabBarAppearance() 
    tabBarAppearance.configureWithDefaultBackground() 
    tabBarAppearance.backgroundColor = UIColor.tabBarBackground 
    UITabBar.appearance().standardAppearance = tabBarAppearance 
}
if #available(iOS 15.0, *) { 
    UITabBar.appearance().scrollEdgeAppearance = tabBarAppearance 
} 

这是唯一能在iOS 15+上获得预期结果的事情。 - Andrew Kestler

0

你也可以像这样从UI编辑器中设置它


0

我总是喜欢在故事板上进行某些设置。这里是 @IBDesignable扩展。

@IBDesignable extension UITabBar {
@IBInspectable var barTintColor: UIColor? {
    set {
        guard let uiColor = newValue else { return }
        UITabBar.appearance().barTintColor = uiColor
    }
    get {
        guard let color = UITabBar.appearance().barTintColor else { return nil }
        return color
    }
}}

-3

Swift 4+版本

UITabBar.appearance().barTintColor = UIColor.red
UITabBar.appearance().tintColor = UIColor.white

1
这个答案是上面链接的副本 https://dev59.com/OFoU5IYBdhLWcg3wRFgh#37626577。 - steveSarsawa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接