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

Swift Charts环形图:如何隐藏数值为0的标注

解决Swift Charts环形图零值标注显示问题

方案1:过滤数据源(推荐)

直接从数据源中移除count为0的元素,既不会生成不可见的SectorMark,也不会渲染对应的标注,性能更优:

// 修改Chart的数据源,过滤掉count为0的项
Chart(data.filter { $0.count > 0 }, id: \.category) { element in
    Plot {
        SectorMark(
            angle: .value("Count", element.count),
            innerRadius: .inset(element.category == .Nominal ? 32 : 40),
            outerRadius: .inset(element.category == .Nominal ? 8 : 0),
            angularInset: 2.0
        )
            .cornerRadius(4)
            .foregroundStyle(by: .value("Category", element.category.rawValue))
            .annotation(position: .overlay, alignment: .center) {
                Text("\(element.count)")
                    .font(.title3)
                    .fontWeight(.semibold)
                    .foregroundStyle(Color.systemGroupedBackground.opacity(0.8))
            }
    }
    .accessibilityLabel(element.category.rawValue.capitalized)
    .accessibilityValue("\(element.count) items")
}
// 其余配置保持不变...

方案2:条件渲染标注(保留数据源)

如果需要保留数据源中的0值项(比如无障碍需求或其他逻辑),可以在annotation内部添加条件判断,仅当count>0时显示文本:

.annotation(position: .overlay, alignment: .center) {
    // 只有count大于0时才显示标注文本
    if element.count > 0 {
        Text("\(element.count)")
            .font(.title3)
            .fontWeight(.semibold)
            .foregroundStyle(Color.systemGroupedBackground.opacity(0.8))
    } else {
        // 空视图不会占用渲染空间
        EmptyView()
    }
}

原理说明

原代码中,即使element.count为0,SectorMark因角度为0不会显示,但annotation仍会被渲染,导致出现多余的0标注。通过上述两种方式,要么直接移除无效数据,要么条件跳过标注渲染,就能解决视觉杂乱的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 14:33:33