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

如何使用iOS 18中Swift Charts的集合数据源版LinePlot?

iOS 18 基于集合数据源的 Charts 使用方法

一、数据源格式要求

集合中的元素可以是任意自定义模型,只要你能从中提取出符合Plottable协议的x、y值即可。系统自带的Int、Double、Date、CGFloat等类型默认遵循Plottable,可直接使用。

如果用自定义模型,不需要让模型本身遵循Plottable,只需在映射时取出模型中类型为Plottable的字段(比如x、y属性)就行。

二、具体实现示例

1. 定义自定义数据模型(可选)

如果需要存储多维度数据,可自定义结构体:

struct SalesData {
    let date: Date
    let revenue: Double
    let region: String
}

这里date和revenue都符合Plottable,可直接作为图表的轴值。

2. 准备数据源

// 模拟业务数据
let sampleData: [SalesData] = [
    SalesData(date: Calendar.current.date(byAdding: .day, value: -6, to: Date())!, revenue: 1200, region: "North"),
    SalesData(date: Calendar.current.date(byAdding: .day, value: -5, to: Date())!, revenue: 900, region: "North"),
    SalesData(date: Calendar.current.date(byAdding: .day, value: -4, to: Date())!, revenue: 1500, region: "North"),
    SalesData(date: Calendar.current.date(byAdding: .day, value: -3, to: Date())!, revenue: 1100, region: "North"),
    SalesData(date: Calendar.current.date(byAdding: .day, value: -2, to: Date())!, revenue: 1800, region: "North"),
    SalesData(date: Calendar.current.date(byAdding: .day, value: -1, to: Date())!, revenue: 1400, region: "North"),
    SalesData(date: Date(), revenue: 2000, region: "North")
]

3. 用集合初始化图表

以LineChart为例,直接传入集合,再在闭包中映射每个数据点到图表系列的x、y值:

import SwiftUI
import Charts

struct SalesChartView: View {
    let salesData: [SalesData]
    
    var body: some View {
        LineChart(data: salesData) { dataPoint in
            LineChartSeries(
                x: dataPoint.date,
                y: dataPoint.revenue
            )
            .foregroundStyle(.blue)
            .symbol(.circle)
        }
        .chartXAxis {
            AxisMarks(position: .bottom) { value in
                AxisGridLine()
                AxisTick()
                AxisLabel(format: .dateTime.day().month(), centered: true)
            }
        }
        .chartYAxis {
            AxisMarks(position: .leading) { value in
                AxisGridLine()
                AxisTick()
                AxisLabel()
            }
        }
        .padding()
    }
}

4. 直接使用基础类型集合

如果不需要自定义模型,用元组数组也能快速实现:

let simpleData: [(Double, Double)] = [(1, 5), (2, 3), (3, 8), (4, 6), (5, 9)]

LineChart(data: simpleData) { point in
    LineChartSeries(x: point.0, y: point.1)
}

三、关键注意点

  • 若要将自定义类型用作轴值,需手动实现Plottable协议,示例:
enum ProductCategory: String, Plottable {
    case electronics, clothing, home
    
    var primitivePlottable: String { rawValue }
    static var axisDescriptor: AxisDescriptor {
        AxisDescriptor(name: "Category")
    }
}
  • 如果使用SwiftUI的Observable集合(比如@State var data: [SalesData]),图表会随数据变化自动更新,无需额外处理。
  • BarChart、AreaChart等其他类型图表的集合使用逻辑一致,都是传入数据源后在闭包中映射到对应系列的轴值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 17:02:47