Search code examples
swiftxcodeswiftuilottieloading-animation

How do I implement a loading animation with SwiftUI?


I already have an animation made in AfterEffects that I think Lottie can turn into a format I can use for my app. What I am wondering is how can I make the app start performing this animation when it is opened until the app is done loading?


Solution

  • Simply show the animation view instead of your content view while it's loading

    example:

    struct ContentView: View {
        @State var isLoading = true
        
        var body: some View {
            VStack {
                if isLoading {
                    LoadingView()
                } else {
                    DoneLoadingView()
                }
            }.onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                    isLoading = false
                }
            }
        }
    }
    
    struct LoadingView: View {
        var body: some View {
            ProgressView()
        }
    }
    
    struct DoneLoadingView: View {
        var body: some View {
            VStack {
                Text("Hello, world!")
            }
        }
    }