Skip to content

Instantly share code, notes, and snippets.

@xcadaverx
Created August 31, 2022 22:44
Show Gist options
  • Save xcadaverx/260382406193ec621b6e00c7ad14d243 to your computer and use it in GitHub Desktop.
Save xcadaverx/260382406193ec621b6e00c7ad14d243 to your computer and use it in GitHub Desktop.
[Spinner] a simple loading spinner for SwiftUI
struct Spinner: View {
var outerColor = Color.blue
var innerColor = Color.red
@State private var isAnimating = false
var body: some View {
GeometryReader { proxy in
ZStack {
self.trimmedCircle(color: self.outerColor, clockwise: true, scale: 1.0, proxy: proxy)
self.trimmedCircle(color: self.innerColor, clockwise: false, scale: 0.75, proxy: proxy)
}
}
.frame(idealWidth: 100, idealHeight: 100)
.onAppear { self.isAnimating = true }
}
private func trimmedCircle(color: Color, clockwise: Bool, scale: CGFloat, proxy: GeometryProxy) -> some View {
let start: Double = clockwise ? 360 : 0
let end: Double = clockwise ? 0 : 360
let borderWidth = min(proxy.size.width, proxy.size.height) / 14
return Circle()
.inset(by: borderWidth / 2)
.scale(scale)
.trim(from: 0.1, to: 0.9)
.stroke(color, lineWidth: borderWidth)
.rotationEffect(.degrees(isAnimating ? start : end))
.animation(repeatingAnimation)
}
private let repeatingAnimation = Animation
.linear(duration: 1.0)
.repeatForever(autoreverses: false)
}
```
struct ContentView: View {
var body: some View {
Spinner().fixedSize()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment