Spinner

SwiftUIAnimationsexamples

👁️ 預覽

📗 參考:Thinking in SwiftUI, Ch. 6: Animations (p.113)

import SwiftUI

// implicit animation
struct Spinner: View {
    // ⭐️ view state
    @State private var animating = false 
    var body: some View { 
        Image(systemName: "rays") 
            // ⭐️ spin
            .rotationEffect(animating ? .degrees(360) : .zero) 
            // ⭐️ forever (without autoreverse)
            .animation(.linear(duration: 2).repeatForever(autoreverses: false))
            // ⭐️ immediately
            .onAppear { self.animating = true }
    }
}

// explicit animation
struct Spinner2: View {
    // ⭐️ view state
    @State private var animating = false 
    var body: some View { 
        Image(systemName: "rays")
            .foregroundColor(.orange)
            // ⭐️ spin
            .rotationEffect(animating ? .degrees(360) : .zero) 
            // ⭐️ immediately
            .onAppear {
                // ⭐️ forever (without autoreverse)
                withAnimation(.linear(duration: 2).repeatForever(autoreverses: false)) {
                    self.animating = true 
                }
            }
    }
}

Last updated

Was this helpful?