1
3

【SwiftUI】棒グラフを選択できるようにする

Posted at

はじめに

前回、円グラフを選択できるようにしました

今回は棒グラフを選択できるようにしてみます。

サンプルアプリ

Simulator Screen Recording - iPhone 15 - 2024-01-19 at 20.51.46.gif

実装

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:)で同じことができます。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3