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

iOS Swift中如何为指定tabBarItem设置绿色圆点徽章?

解决TabBarItem绿色圆点徽章显示为红色的问题

问题原因

  • 代码存在笔误:badge value 应为 badgeValue,该错误会导致后续文本属性设置无法生效。
  • 直接通过setBadgeTextAttributes设置文本颜色,在部分iOS版本或默认TabBar样式下可能被系统默认样式覆盖。

修正方案

使用attributedBadgeValue直接设置带颜色的富文本徽章,这种方式更稳定可靠,能避免系统样式干扰:

// 清除默认徽章背景色
xxxx.tabBarItem.badgeColor = .clear

// 构建绿色圆点的富文本
let attributedString = NSAttributedString(
    string: "●",
    attributes: [.foregroundColor: UIColor.green]
)
// 设置富文本徽章
xxxx.tabBarItem.attributedBadgeValue = attributedString

备选修正方式(修正笔误后保留原逻辑)

若坚持使用原有的文本属性设置方式,需先修正笔误,同时确保TabBar未使用自定义样式覆盖系统徽章渲染:

// 修正笔误
xxxx.tabBarItem.badgeValue = "●"
xxxx.tabBarItem.badgeColor = .clear

let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.green]
// 为所有状态统一设置文本属性
xxxx.tabBarItem.setBadgeTextAttributes(attributes, for: .normal)
xxxx.tabBarItem.setBadgeTextAttributes(attributes, for: .selected)
xxxx.tabBarItem.setBadgeTextAttributes(attributes, for: .highlighted)
xxxx.tabBarItem.setBadgeTextAttributes(attributes, for: .disabled)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:35:02