Skip to content

Instantly share code, notes, and snippets.

@jan-ekholm
Created December 5, 2023 10:20
Show Gist options
  • Save jan-ekholm/abb34c0388f51335e0bf4c4a5a4954a5 to your computer and use it in GitHub Desktop.
Save jan-ekholm/abb34c0388f51335e0bf4c4a5a4954a5 to your computer and use it in GitHub Desktop.
SwiftUI bar chart bug
import SwiftUI
import Charts
struct Value: Hashable {
let x: Int
let y: Int
}
struct ContentView: View {
let values: [Value]
let colors: [Color] = [.red, .green, .blue]
var body: some View {
VStack {
Chart {
ForEach(values, id: \.self) { value in
BarMark(
x: .value("X", value.x),
y: .value("Y", value.y),
width: .fixed(16) // a smaller (or none) fixed size works better
)
.foregroundStyle(colors[value.x % colors.count])
}
}
.chartScrollableAxes(.horizontal)
Chart {
ForEach(values, id: \.self) { value in
BarMark(
x: .value("X", value.x),
y: .value("Y", value.y),
width: .fixed(25) // a larger fixed size triggers the bug quicker
)
.foregroundStyle(colors[value.x % colors.count])
}
}
.chartScrollableAxes(.horizontal)
}
.padding()
}
}
#Preview {
var rnd = SystemRandomNumberGenerator()
// increase to bring out the bug quicker. Smaller values fit easier
let numberOfValues = 50
var values: [Value] = []
for index in 0 ..< numberOfValues {
values.append(Value(x: index, y: Int(rnd.next() % 50)))
}
return ContentView(values: values)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment