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

如何在Swift Charts中实现类似苹果健康App的图表标注?

能否用Swift Charts实现苹果健康App风格的带标注折线图?

可以实现。下面基于你提供的代码进行修改,就能接近苹果健康App中心肺适能图表的样式,核心是添加数据标注、优化线条与轴的视觉效果:

修改后的完整代码

// 数据模型
struct TestWeight: Identifiable {
    var id = UUID()
    var weight: Double
    var date: Date

    init(id: UUID = UUID(), weight: Double, day: Int) {
        self.id = id
        self.weight = weight
        let calendar = Calendar.current
        self.date = calendar.date(from: DateComponents(year: 2023, month: 10, day: day))!
    }
}

// 测试数据
var weight: [TestWeight] = [
    TestWeight(weight: 69.4, day: 2),
    TestWeight(weight: 69.2, day: 3),
    TestWeight(weight: 70.0, day: 4),
    TestWeight(weight: 69.7, day: 5),
    TestWeight(weight: 69.0, day: 6),
    TestWeight(weight: 68.8, day: 7),
    TestWeight(weight: 68.0, day: 8)
]

Chart {
    // 折线主线条
    ForEach(weight) { data in
        LineMark(
            x: .value("日期", data.date, unit: .day),
            y: .value("体重", data.weight)
        )
        .foregroundStyle(Color.accentColor) // 用系统强调色贴合苹果原生风格
        .lineStyle(StrokeStyle(lineWidth: 2))
    }
    
    // 数据点标记
    ForEach(weight) { data in
        PointMark(
            x: .value("日期", data.date, unit: .day),
            y: .value("体重", data.weight)
        )
        .symbolSize(12)
        .foregroundStyle(Color.white)
        .border(Color.accentColor, width: 2)
    }
    
    // 数据标注(模拟健康App的数值显示)
    ForEach(weight) { data in
        TextMark(
            x: .value("日期", data.date, unit: .day),
            y: .value("体重", data.weight),
            text: .value("体重值", String(format: "%.1f", data.weight))
        )
        .font(.caption)
        .offset(y: -15) // 让标注显示在数据点上方,避免遮挡折线
    }
}
.frame(height: 200) // 增高图表预留标注空间
.chartXAxis {
    AxisMarks(values: .stride(by: .day)) { _ in
        AxisTick(length: 4)
        AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5, dash: [2])) // 虚线网格线贴合健康App风格
        AxisValueLabel(format: .dateTime.weekday(.abbreviated), centered: true)
            .font(.caption)
    }
}
.chartYAxis {
    AxisMarks(position: .leading) { _ in
        AxisTick(length: 4)
        AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5, dash: [2]))
        AxisValueLabel().font(.caption)
    }
}
.chartYScale(domain: 62...70)
.background(Color(.systemGroupedBackground)) // 背景色贴近健康App的浅色布局

关键修改说明

  • 添加数据标注:通过TextMark在每个数据点上方展示具体数值,调整偏移量避免遮挡折线
  • 优化数据点样式:采用白色填充+彩色边框的圆点,匹配健康App的视觉细节
  • 调整线条与网格:将网格线改为虚线,线条宽度设为2,还原苹果的细腻设计风格
  • 适配系统风格:使用系统强调色和背景色,保持与原生App一致的视觉体验
  • 优化字体层级:轴标签和标注采用小字号,契合健康App的简洁布局

(苹果健康App中心肺适能图表样式参考:折线平滑、数据点带白色边框、每个点上方标注数值,网格线为浅灰色虚线,整体风格简洁干净)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 06:54:55