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

SwiftUI Charts 点击标注始终不更新问题求助

问题排查与解决

核心问题

你把带标注(Annotation)的RuleMark写在了Chart(entries) { entry in ... }的闭包内部,这会导致每一条数据条目都会生成一个相同x位置的RuleMark和对应的Annotation。这些标注会重叠在一起,最终显示的是循环中最后一个entry的内容,所以无论点击图表哪个位置,都只会看到同一个数据。

修正代码

调整Chart结构,将带Annotation的RuleMark移到循环外部,并根据选中的日期匹配对应的数据条目:

@State var selectedDate: Date? = nil

var body: some View {
  Chart(entries) { entry in 
    LineMark(
      x: .value("Date", Date(milliseconds: entry.timestamp)),
      y: .value("Glucose", entry.value)
    )
    RuleMark(y: .value("high", 180))
      .foregroundStyle(.red)
    RuleMark(y: .value("low", 60))
      .foregroundStyle(.red)
  }
  // 把带Annotation的RuleMark移到Chart闭包外部
  .overlay {
    if let selectedDate = selectedDate {
      // 根据选中日期匹配对应的entry(用60秒容错处理时间精度偏差)
      let matchedEntry = entries.first {
        abs(Date(milliseconds: $0.timestamp).timeIntervalSince(selectedDate)) < 60
      }
      
      Chart {
        RuleMark(x: .value("Date", selectedDate))
          .annotation(
            position: .automatic,
            overflowResolution: .init(x: .fit(to: .chart), y: .disabled)
          ) {
            if let entry = matchedEntry {
              GlucoseAnnotation(entry: entry)
            }
          }
      }
    }
  }
  .chartXSelection(value: $selectedDate)
  .padding()
}

关键说明

  • 将标注相关的RuleMark从数据循环中移出,确保只生成一个标注,避免重叠覆盖
  • 通过时间差容错匹配选中日期对应的数据条目,解决图表选中时间与数据点时间的细微偏差问题
  • 仅在找到匹配条目时渲染标注,避免空数据异常显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 15:05:00