You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift:如何通过代码修改UITabItem的角标颜色

编程修改barItem角标颜色(替换默认红色效果)

需要自定义TabBar上barItem的角标颜色,替换系统默认的红色显示,参考效果如下:
角标示例

iOS 10+ 原生API实现

苹果在iOS 10之后正式开放了角标颜色的修改接口,不需要做任何特殊处理,直接设置badgeColor属性即可:

  • Objective-C 代码
// 单个item设置自定义角标颜色
self.tabBarItem.badgeColor = [UIColor colorWithRed:0.2 green:0.6 blue:0.9 alpha:1];
// 设置角标显示内容
self.tabBarItem.badgeValue = @"3";

// 全局统一设置所有tabBarItem的角标颜色
[UITabBarItem appearance].badgeColor = [UIColor orangeColor];
  • Swift 代码
// 单个item设置
tabBarItem.badgeColor = .systemPurple
tabBarItem.badgeValue = "99+"

// 全局统一设置
UITabBarItem.appearance().badgeColor = .systemPurple

如果需要调整角标上的文字颜色,可以搭配badgeTextAttributes属性设置:

// 设置角标文字为白色
tabBarItem.setBadgeTextAttributes([.foregroundColor: UIColor.white], for: .normal)

iOS 9及以下低版本兼容方案

如果需要适配iOS 10以下的系统,系统没有开放直接修改的API,可以通过遍历TabBar子视图找到角标控件修改背景色:

  • Objective-C 代码
- (void)updateBadgeColor:(UIColor *)targetColor forTabBar:(UITabBar *)tabBar {
    for (UIView *tabBarButton in tabBar.subviews) {
        if (![NSStringFromClass([tabBarButton class]) isEqualToString:@"UITabBarButton"]) {
            continue;
        }
        for (UIView *badgeView in tabBarButton.subviews) {
            if ([NSStringFromClass([badgeView class]) isEqualToString:@"_UIBadgeView"]) {
                badgeView.backgroundColor = targetColor;
                break;
            }
        }
    }
}

调用时机注意在角标值设置完成、TabBar布局完成后调用,否则可能找不到对应角标视图。

  • Swift 代码
func updateBadgeColor(_ color: UIColor, for tabBar: UITabBar) {
    for tabBarButton in tabBar.subviews {
        guard String(describing: type(of: tabBarButton)) == "UITabBarButton" else { continue }
        for badgeView in tabBarButton.subviews {
            if String(describing: type(of: badgeView)) == "_UIBadgeView" {
                badgeView.backgroundColor = color
                break
            }
        }
    }
}

注意:低版本遍历私有控件的方式在iOS系统版本迭代时可能出现兼容问题,如果没有特殊低版本适配需求,优先使用iOS 10+提供的原生API实现。

内容的提问来源于stack exchange,提问作者DMD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 02:31:06