Post

SwiftUI Chart Annotation

```swift import SwiftUI import Charts import Foundation

struct SimpleAnnotationView: View {

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
private var intakes: [Intake] = [
    Intake(timestamp: .now, dayPeriod: true, amount: 55),
    Intake(timestamp: Calendar.current.date(bySetting: .day, value: 1, of: .now)!, dayPeriod: true, amount: 55),
]
@State private var rawSelectedDate: Date?
var selectedDate: Date? {
    guard let rawSelectedDate else { return nil }
    return intakes.first(where: {
        Calendar.current.startOfDay(for:$0.timestamp) == Calendar.current.startOfDay(for: rawSelectedDate)
    })?.timestamp
}

var body: some View {
    Chart {
        ForEach(intakes) { intake in
            BarMark(x: .value("日期", intake.timestamp, unit: .day),
                    y: .value("重量", intake.amount))
        }
        if let selectedDate {
            RuleMark(
                x: .value("Selected", selectedDate, unit: .day)
            )
            .annotation(position: .topLeading) {
                VStack {
                    Text("Annotation")
                        .font(.caption)
                        .padding(5)
                        .background(RoundedRectangle(cornerRadius: 5).fill(Color.green))
                }
            }
            .zIndex(-1)
        }
    }
    .chartXSelection(value: $rawSelectedDate)
} }

#Preview { SimpleAnnotationView() }```

This post is licensed under CC BY 4.0 by the author.