当我们点击 SwiftUI 图表中的 BarView 时如何更改它的颜色

Lee*_*ela 6 swiftui swiftui-charts

我创建了如下所示的图表视图。我想知道当用户点击栏时如何更改栏标记。

Chart {
    ForEach(Data.lastOneHour, id: \.day) {
        BarMark(
            x: .value("Month", $0.day, unit: .hour),
            y: .value("Duration", $0.duration)
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

我看到.onTap修改器不可用BarMark,并且我看不到任何方法来访问条形标记并使用手势位置应用颜色GeometryReader

wor*_*dog 6

您可以尝试这种方法,当用户点击该栏时,使用 achartOverlay和变量来更改栏颜色。select

struct ContentView: View {
    let measurement: [Measurement] = [
        Measurement(id: "1", val: 11.2),
        Measurement(id: "2", val: 22.2),
        Measurement(id: "3", val: 38.2)
    ]
    
    @State var select = "0"
    
    var body: some View {
        Chart(measurement) { data in
            BarMark(x: .value("Time", data.id), y: .value("val", data.val))
                .foregroundStyle(select == data.id ? .red : .blue)
        }
        .chartOverlay { proxy in
            GeometryReader { geometry in
                ZStack(alignment: .top) {
                    Rectangle().fill(.clear).contentShape(Rectangle())
                        .onTapGesture { location in
                            doSelection(at: location, proxy: proxy, geometry: geometry)
                        }
                }
            }
        }
    }
    
    func doSelection(at location: CGPoint, proxy: ChartProxy, geometry: GeometryProxy) {
        let xPos = location.x - geometry[proxy.plotAreaFrame].origin.x
        guard let xbar: String = proxy.value(atX: xPos) else { return }
        select = xbar
    }
    
}

struct Measurement: Identifiable {
    var id: String
    var val: Double
}
Run Code Online (Sandbox Code Playgroud)