You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Swift Charts实现柱状图从左到右的生长动画?

Swift Charts 实现柱状图从左到右生长动画

问题说明

原始柱状图无动画效果,尝试添加动画时,使用xStart/xEnd结合position(by:)的方案导致柱状图从中间而非左侧边界生长。

修正方案

问题根源在于position(by: .value("Alignment", 0))强制柱状图居中对齐,去掉该修饰符后,结合xStart固定为0、xEnd随进度值动态变化,即可实现从左到右的自然生长动画:

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)
        }
        .chartLegend(.hidden)
        .chartXAxis(.hidden)
        .chartYAxis {
            AxisMarks { _ in
                AxisValueLabel()
                    .foregroundStyle(Color.black)
            }
        }
        .aspectRatio(1, contentMode: .fit)
        .onAppear {
            withAnimation(.easeOut(duration: 1.5)) {
                progress = 1
            }
        }
    }
}

另一种简化实现

也可以直接对BarMark的x值进行动画,无需拆分xStart/xEnd,代码更简洁:

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

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

关键说明

  • 移除position(by:)修饰符,避免柱状图被强制居中对齐
  • 通过progress状态变量控制柱状图长度,配合withAnimation实现平滑过渡
  • 两种方案均能实现从左到右的生长效果,可根据需求选择

内容的提问来源于stack exchange,提问作者ixx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 20:26:07