SwiftUI中如何为LineMark图表的每个数据点添加温度标签
SwiftUI Chart 数据点温度文本全量显示解决方案
问题原因
你当前的写法中,每个LineMark仅包含单个数据点,SwiftUI Chart的默认逻辑会合并同系列的annotation,导致仅第一个数据点的文本显示。
解决方案
方案一:使用PointMark单独处理标注(推荐)
将折线绘制与数据点标注拆分,用LineMark绘制整条折线,PointMark为每个数据点添加符号和温度文本:
Chart { ForEach(temperatures, id: \.tempType) { series in // 绘制完整折线 LineMark( x: .value("Day", series.data.map(\.day)), y: .value("Temps", series.data.map(\.temp)) ) .interpolationMethod(.catmullRom) .foregroundStyle(by: .value("TemperatureType", series.tempType)) .lineStyle(.init(lineWidth: 5)) // 为每个数据点添加符号和温度标注 ForEach(series.data) { element in PointMark( x: .value("Day", element.day), y: .value("Temps", element.temp) ) .symbol { Circle() .fill(.yellow) .frame(width: 10) .shadow(radius: 2) } .annotation(position: .overlay, alignment: .bottom) { Text("\(element.temp)") .font(.caption) .foregroundColor(.black) } } } }
方案二:修复原有LineMark的annotation绑定
如果坚持保留逐个LineMark的写法,需为annotation明确绑定坐标,避免Chart自动合并:
Chart { ForEach(temperatures, id: \.tempType) { series in ForEach(series.data) { element in LineMark( x: .value("Day", element.day), y: .value("Temps", element.temp) ) .interpolationMethod(.catmullRom) .foregroundStyle(by: .value("TemperatureType", series.tempType)) .symbol { Circle() .fill(.yellow) .frame(width: 10) .shadow(radius: 2) } .lineStyle(.init(lineWidth: 5)) // 明确绑定坐标,确保每个annotation独立显示 .annotation(position: .overlay, alignment: .bottom) { Text("\(element.temp)") } .position(x: .value("Day", element.day), y: .value("Temps", element.temp)) } } }
内容的提问来源于stack exchange,提问作者hoptown
相关产品推荐
相关产品推荐

