0

I have a Chart where I'm trying to add annotation for a bar when tapped. The annotation appears properly~ish. The bars start movig around to different positions once I tap on them.

Here's the code for this?

                        ScrollView(.horizontal, showsIndicators: false) {
                            GroupBox ("Recalls by state") {
                                Chart {
                                    let recallData = statsVM.getRecallsByState(with: recallMockData)
                                    ForEach(recallData, id: \.self) { barMark in
                                        BarMark(
                                            x: .value("Week", barMark.week),
                                            y: .value("Recalls", Double(barMark.count))
                                        )
                                        .foregroundStyle(Color("BorderColor"))
                                        .annotation {
                                            Text(selectedState ?? "nil?")
                                        }
                                    }
                                }
                                .chartOverlay { proxy in
                                    GeometryReader { geometry in
                                        ZStack(alignment: .top) {
                                            Rectangle().fill(.clear).contentShape(Rectangle())
                                                .onTapGesture { location in
                                                    updateSelectedState(at: location, proxy: proxy, geometry: geometry)
                                                }
                                        }
                                    }
                                }
                                .padding()
                                .chartYAxis {
                                    AxisMarks(position: .leading)
                                }
                                .frame(width: 450)
                            }
                        }
                        .frame(height: 250)

    func updateSelectedState(at location: CGPoint, proxy: ChartProxy, geometry: GeometryProxy) {
         let xPosition = location.x - geometry[proxy.plotAreaFrame].origin.x
         guard let state: String = proxy.value(atX: xPosition) else {
             return
         }
        selectedState = state
        selectedCount = statsVM.getRecallsByState(with: coreVM.recallResults).first { $0.week == state }?.count ?? 0
     }

This is very similar to the following post, but the solution did not work. SwiftUI Charts tapping Bar Chart

Robert
  • 809
  • 3
  • 10
  • 19

0 Answers0