If I use the following Swift Charts Chart
anywhere (Xcode Simulator, Playground, etc.) it hangs or crashes. As soon as I remove the chartXVisibleDomain
modifier everything works. Is anybody else experiencing the same issue and/or knows how to fix it? I'm on Xcode Version 15.0 (15A240d).
import SwiftUI
import Charts
struct ContentView: View {
let data: [(day: Date, value: Int)] = [
(Calendar.current.date(byAdding: .day, value: 0, to: .now)!, 1),
(Calendar.current.date(byAdding: .day, value: -1, to: .now)!, 2),
(Calendar.current.date(byAdding: .day, value: -3, to: .now)!, 3),
(Calendar.current.date(byAdding: .day, value: -10, to: .now)!, 4),
(Calendar.current.date(byAdding: .day, value: -20, to: .now)!, 5)
]
var body: some View {
Chart(data, id: \.day) { (day, value) in
BarMark(
x: .value("Date", day, unit: .day),
y: .value("Value", value)
)
}
.chartXVisibleDomain(length: 2)
}
}
By trial and error, I found that the number passed to chartXVisibleDomain
in this case should be in seconds. This kind of makes sense, since Date
is kind of like a wrapper around timeIntervalSince1970
, which is in seconds.
The app hangs probably because you are drawing a really really wide chart - you are saying you only want to see 2 seconds at a time, of the whole 20-day data.
You can do:
.chartXVisibleDomain(length: 86400*2) // 86400 seconds is 24 hours
instead.