swiftui animation spinner in swift

To create a spinner in SwiftUI, you can use the built-in ProgressView element with some customization to make it look like a spinner.

Here is an example code snippet that you can use to create a spinning animation:

main.swift
import SwiftUI

struct Spinner: View {
    @State private var isAnimating = false
    
    var body: some View {
        VStack {
            Circle()
                .trim(from: 0, to: 0.7)
                .stroke(AngularGradient(gradient: .init(colors: [.red, .orange]), center: .center), lineWidth: 8)
                .rotationEffect(Angle(degrees: isAnimating ? 360 : 0))
                .animation(Animation.linear(duration: 1).repeatForever(autoreverses: false))
                .frame(width: 60, height: 60)
            
            Text("Loading...")
                .foregroundColor(.gray)
                .padding(.top, 8)
        }
        .onAppear {
            self.isAnimating = true
        }
    }
}

struct Spinner_Previews: PreviewProvider {
    static var previews: some View {
        Spinner()
    }
}
824 chars
30 lines

This code creates a Circle with a gradient stroke that fills 70% of the circle's circumference. It then rotates the circle with an animation that repeats forever. The text "Loading..." is positioned above the circle.

To start the animation, we set the isAnimating state variable to true in the onAppear closure of the VStack.

gistlibby LogSnag