Created
November 22, 2025 10:36
-
-
Save TariqAlmazyad/70bdb40948df685581d50f6ef3a15379 to your computer and use it in GitHub Desktop.
SwiftUI Chart Animation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // ContentView.swift | |
| // ChartsAnimation | |
| // | |
| // Created by Tariq Almazyad on 20/11/2025. | |
| // | |
| import SwiftUI | |
| import Charts | |
| struct Sales: Identifiable, Hashable, Equatable { | |
| let id = UUID() | |
| var day: String | |
| var count: Int | |
| var isAnimated: Bool = false | |
| static let mock: [Sales] = [ | |
| Sales(day: "Sunday", count: 12), | |
| Sales(day: "Monday", count: 18), | |
| Sales(day: "Tuesday", count: 37), | |
| Sales(day: "Wednesday", count: 15), | |
| Sales(day: "Thursday", count: 27), | |
| Sales(day: "Friday", count: 30), | |
| ] | |
| } | |
| struct ContentView: View { | |
| @State var values: [Sales] = [] | |
| @State var isAnimated: Bool = false | |
| var body: some View { | |
| VStack { | |
| Chart { | |
| ForEach(values, id:\.id) { item in | |
| BarMark( | |
| x: .value("year", item.day), | |
| y: .value("number", item.isAnimated ? item.count : 0) | |
| ).foregroundStyle(by: .value("day", item.day)) | |
| .opacity(item.isAnimated ? 1 : 0) | |
| } | |
| }.frame(height: 300) | |
| .chartYScale(domain: 0...50) | |
| .onAppear { | |
| animateChart() | |
| } | |
| Spacer() | |
| } | |
| .padding() | |
| } | |
| private func animateChart() { | |
| isAnimated.toggle() | |
| values = Sales.mock | |
| $values.enumerated().forEach { index, element in | |
| let delay = Double(index) * 0.2 | |
| DispatchQueue.main.asyncAfter(deadline: .now() + delay) { | |
| withAnimation { | |
| element.wrappedValue.isAnimated = true | |
| } | |
| } | |
| } | |
| } | |
| } | |
| #Preview { | |
| NavigationStack { | |
| ContentView() | |
| .preferredColorScheme(.dark) | |
| .navigationTitle("Chart Animation") | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment