Page 1 of 1

Wie animiere ich die Balken mit Swift Charts von links nach rechts?

Posted: 23 Jan 2025, 07:05
by Guest
Ich habe dieses Diagramm:

Code: Select all

private struct ChartView: View {
let sections: [BoughtItemsByTagSection]

var body: some View {
Chart(sections) { section in
BarMark(x: .value("Price", section.header.totalPrice),
y: .value("Category", section.header.name))
.foregroundStyle(Theme.accentSec)
}
.chartLegend(.hidden)
.chartXAxis(.hidden)
.chartYAxis {
AxisMarks { _ in
AxisValueLabel()
.foregroundStyle(Color.black)
}
}
.aspectRatio(1, contentMode: .fit)
}
}

wobei ich eine einfache Animation möchte, die die horizontalen Balken von links nach rechts vergrößert. Ich habe mehrere Versuche unternommen, der nächste:

Code: Select all

private struct ChartView: View {
let sections: [BoughtItemsByTagSection]
@State private var progress: Float = 0

var body: some View {
Chart(sections) { section in
BarMark(
xStart: .value("Start", 0),
xEnd: .value("Price", section.header.totalPrice * progress),
y: .value("Category", section.header.name)
)
.foregroundStyle(Theme.accentSec)
.position(by: .value("Alignment", 0))
}
.chartLegend(.hidden)
.chartXAxis(.hidden)
.chartYAxis {
AxisMarks { _ in
AxisValueLabel()
.foregroundStyle(Color.black)
}
}
.aspectRatio(1, contentMode: .fit)
.onAppear {
animateChart()
}
}

private func animateChart() {
progress = 0 // Start from zero
withAnimation(.easeOut(duration: 1.5)) {
progress = 1
}
}
}
Aber es gibt das Problem, dass die Balken von der Mitte aus wachsen und nicht von links, was der natürliche Anker für dieses Diagramm ist. Wie lässt man sie vom linken Rand aus wachsen?