如何以编程方式更改标签栏的背景颜色?

How to change the background color of tab bar programatically?

我的目标很简单,把tab bar的默认背景色改成我自己的颜色。

例如,默认看起来像这样

我创建了自己的 UITabBarController 子类,这样我就不需要更改每个 UIViewController 的颜色

import UIKit

class MyTabController: UITabBarController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBar.backgroundColor = .black
    }
}

结果和我预想的不一样

我想可能是颜色的问题,然后我换了一个自定义的UIColor,颜色看起来完全一样。

我也试过更改条形图颜色,但它会在激活时更改图标的颜色,而不是背景

self.tabBar.tintColor = UIColor(red:1.00, green:0.23, blue:0.19, alpha:1.0)

结果会是

我做错了什么?

您应该使用 self.tabBar.barTintColor 或查看 UIBarStyleself.tabBar.barStyle 看看是否可行。

我的应用程序遇到了同样的问题,但我想在标签栏背景中设置一个渐变图像,我想出了以下方法: 在 applicationDidFinishLaunching 方法中,我创建了一个函数来绘制渐变,并使用我的 UITabBarController 实例根据设备的宽度设置正确的渐变框架。

- (UIImage *)drawGradientInView:(UITabBarController *) tabBarVC {
    CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(CGRectGetMinX(tabBarVC.tabBar.frame), CGRectGetMinY(tabBarVC.tabBar.frame), CGRectGetWidth(tabBarVC.view.frame), CGRectGetHeight(tabBarVC.tabBar.frame));

    //set up your gradient
    //......

    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return gradientImage;
}

获取 UITabBarController 实例

UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].windows.firstObject.rootViewController;

设置渐变

[UITabBar appearance].backgroundImage = [self drawGradientInView:tabVC];

我不确定这是否是正确的方法,但它确实对我有用。