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

iOS18 Widget中如何仅为Swift Chart的Bar Mark设置强调色?

iOS 18 Widget中仅让Swift Chart的Bar Mark应用主屏幕着色

我正在更新Widget以支持iOS 18的主屏幕着色自定义选项,尝试使用.widgetAccentable()时遇到问题:将这个修饰符应用于整个Chart会让所有元素(条形标记、标签、坐标轴等)都被着色,但我只想让Bar Mark使用强调色,其他元素保持黑白单色。

当前代码:

Chart {
    ForEach(data, id: \.id) { day in
        BarMark(
            x: .value("###", day.date, unit: .day),
            y: .value("###", day.value)
        )
        .cornerRadius(10.0)
        .foregroundStyle(Color.blue.gradient)
        .alignsMarkStylesWithPlotArea()
        .annotation {
            Text(day.value.description)
                .font(.subheadline)
        }
    }
}
.widgetAccentable()
.chartYAxis(.hidden)
.chartXAxis {
    AxisMarks(values: .stride(by: .day)) { value in
        AxisValueLabel(format: Date.FormatStyle().weekday(.short), centered: true)
    }
}

解决方案

不要给整个Chart添加.widgetAccentable(),而是直接用WidgetAccentColor设置Bar Mark的前景色,同时显式指定其他元素的颜色为系统主色(确保保持黑白单色):

修改后的代码:

Chart {
    ForEach(data, id: \.id) { day in
        BarMark(
            x: .value("日期", day.date, unit: .day),
            y: .value("数值", day.value)
        )
        .cornerRadius(10.0)
        // 使用WidgetAccentColor响应主屏幕着色,可添加fallback颜色
        .foregroundStyle(WidgetAccentColor.or(.blue).gradient)
        .alignsMarkStylesWithPlotArea()
        .annotation {
            Text(day.value.description)
                .font(.subheadline)
                .foregroundStyle(Color.primary) // 标签保持系统主色
        }
    }
}
.chartYAxis(.hidden)
.chartXAxis {
    AxisMarks(values: .stride(by: .day)) { value in
        AxisValueLabel(format: Date.FormatStyle().weekday(.short), centered: true)
            .foregroundStyle(Color.primary) // 坐标轴标签保持系统主色
    }
}

说明

  • WidgetAccentColor会自动适配iOS 18的主屏幕自定义着色,同时可以用.or()方法指定 fallback 颜色(比如原来的蓝色),兼容未开启自定义着色的场景。
  • 通过给标签、坐标轴显式设置Color.primary,确保这些元素保持系统默认的黑白单色,不会被强调色影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 05:43:14