はじめに
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
}
}
}
}
}