はじめに
前回、円グラフを選択できるようにしました
今回は棒グラフを選択できるようにしてみます。
サンプルアプリ
実装
import SwiftUI
import Charts
struct Temperature {
let day: Int
let max: Double
let min: Double
}
struct ContentView: View {
@State private var temperatures: [Temperature] = [
.init(day: 1, max: 17, min: 13),
.init(day: 2, max: 25, min: 10),
.init(day: 3, max: 12, min: 11),
.init(day: 4, max: 21, min: 11),
.init(day: 5, max: 10, min: 6)
]
+ @State private var selectedDay: Int?
var body: some View {
Chart {
ForEach(temperatures, id: \.day) { temperature in
BarMark(
x: .value("day", temperature.day),
y: .value("max", temperature.max),
width: 30
)
.opacity(selectedDay == nil ? 1.0 : temperature.day == selectedDay ? 1.0 : 0.3)
}
}
+ .chartXSelection(value: $selectedDay)
.frame(width: 300, height: 300)
}
}
おわり
今回の棒グラフは縦なのでchartXSelection(value:)
を使用しています。
棒グラフが横の場合はchartYSelection(value:)
で同じことができます。