Using Charts in SwiftUI to create a horizontal bar chart, if the text of the legend is sufficiently long, the text overflows outside of the view rather than wrapping or moving to the next line. (can see problem when running code on on iPhone)
Is this a bug or am I doing something incorrectly?
I can use .clipped()
to ensure the legend doesn't overflow. But that doesn't fully solve the problem because the text is then just cut off.
import Charts
import SwiftUI
struct ChartData: Identifiable {
let id: Int
let title: String
let count: Double
let color: Color
}
struct ContentView: View {
private let data = [
ChartData(id: 1, title: "Item 1", count: 4, color: .yellow),
ChartData(id: 2, title: "Item 2 With a Long Title and then some more", count: 6, color: .blue),
ChartData(id: 3, title: "Item 3 With a Long Title", count: 12, color: .green)
]
private let chartHeight: CGFloat = 40
private let chartCornerRadius: CGFloat = 5
var body: some View {
VStack {
Chart(data) { item in
BarMark(
x: .value("Count", item.count),
stacking: .normalized
)
.foregroundStyle(by: .value("Title", item.title))
}
.chartXAxis(.hidden)
.chartYAxis(.hidden)
.chartLegend(.visible)
.chartPlotStyle { chartContent in
chartContent
.frame(height: chartHeight)
}
.chartForegroundStyleScale(range: data.map { $0.color })
}
.padding()
}
}
#Preview {
ContentView()
}