LoginSignup
0
1

More than 1 year has passed since last update.

【SwiftUI】Loading時のアニメーションを追加する

Posted at

はじめに

Loading時のアニメーションを追加する

環境

Xcode: 13.3.1

Code

LoadingView.swift
struct LoadingView: View {
    
    @State var isLoading : Bool = false
    var body: some View {
        VStack{
            Button {
                Task{
                        isLoading = true
                        try await Task.sleep(nanoseconds: 5_000_000_000)
                        isLoading = false
                }
            } label: {
                Group{
                    if isLoading {
                        ActivityIndicator()
                    } else {
                        Text("Click")
                            .foregroundColor(.white)
                    }
                }
                .padding()
                .frame(width: 240, height: 80, alignment: .center)
            }
            .background(RoundedRectangle(cornerRadius: 16).strokeBorder(Color.white, lineWidth: 2.5))
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.black.edgesIgnoringSafeArea(.all))
    }
}
ActivityIndicator.swift
struct ActivityIndicator: View {
    
    @State var currentDegrees = 0.0
    
    let colorGradient = LinearGradient(gradient: Gradient(colors: [
        Color.yellow,
        Color.yellow.opacity(0.75),
        Color.yellow.opacity(0.5),
        Color.yellow.opacity(0.2),
        .clear]),
        startPoint: .leading, endPoint: .trailing)
    
    var body: some View {
        Circle()
            .trim(from: 0.0, to: 0.85)
            .stroke(colorGradient, style: StrokeStyle(lineWidth: 5))
            .frame(width: 40, height: 40)
            .rotationEffect(Angle(degrees: currentDegrees))
            .onAppear {
                Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { _ in
                    withAnimation {
                        self.currentDegrees += 10
                    }
                }
            }
    }
}

動作画面

Sep-05-2022 21-44-33.gif

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1