Search code examples
iosswiftanimationswiftuiswiftcharts

How to animate the bars from left to right with Swift Charts?


I've this chart:

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)
    }
}

where I want a simple animation that grows the horizontal bars from left to right. I've done multiple attempts, the closest one:

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
        }
    }
}

but it has the problem that the bars grow from the center instead of from the left, which is the natural anchor for this chart. How to make them grow from the left border?


Solution

  • You have not specified an X axis domain for your chart, and so SwiftUI automatically finds one that fits your data. The reason why the bars grows from the middle is because the automatically-determined domain behaves weirdly when all your data points are 0. The animation interpolates between that weird domain to the desired domain.

    If you start the animation at progress = 0.1, you can see that the bars do not animate at all. Remove .chartXAxis(.hidden), and you will see that it is actually the X axis' scale that is being animated!

    So just fix a domain. Find the largest value of your data and use that as the maximum value of the X axis.

    let max = sections.map(\.header.totalPrice).max()!
    
    // ...
    
    .chartXScale(domain: .automatic(dataType: Float.self, modifyInferredDomain: { $0 = [0, max] }))
    

    You don't necessarily have to use the xStart/xEnd initialiser. The bar marks in the first code snippet works too, if you multiply by progress.

    BarMark(
        x: .value("Price", section.header.totalPrice * progress),
        y: .value("Category", section.header.name)
    )
    

    An alternative is to animate the offsets of the xEnds. Offset the xEnds of the all the bars so they are invisible, then animate that offset to 0. You can use a GeometryReader to figure out how much you should offset them by, though this is an upper bound - shorter bars will take longer before they first appear. In other words, all the bars will grow at the same speed.

    GeometryReader { geo in
        Chart(sections) { section in
            BarMark(
                xStart: .value("Start", 0),
                xEnd: .value("Price", section.header.totalPrice),
                y: .value("Category", section.header.name)
            )
            .offset(xEnd: -geo.size.width * (1 - progress))
        }
        // ...
    }