Skip to content

Instantly share code, notes, and snippets.

@mdb1
Last active March 11, 2023 20:11
Show Gist options
  • Save mdb1/0602f0e4939995db3e5463f64c11a550 to your computer and use it in GitHub Desktop.
Save mdb1/0602f0e4939995db3e5463f64c11a550 to your computer and use it in GitHub Desktop.
DelayAppearanceModifier
struct DelayAppearanceModifier: ViewModifier {
var animation: Animation
var delay: TimeInterval
var offset: CGSize
@State private var isShown: Bool = false
func body(content: Content) -> some View {
content
.opacity(isShown ? 1 : 0)
.offset(x: isShown ? 0 : offset.width, y: isShown ? 0 : offset.height)
.task { withAnimation { isShown = true } }
.animation(animation.delay(delay), value: isShown)
}
}
extension View {
func delayAppearance(
with animation: Animation = .spring(),
by duration: TimeInterval,
offset: CGSize = .init(width: 0, height: 32)
) -> some View {
modifier(
DelayAppearanceModifier(
animation: animation,
delay: duration,
offset: offset
)
)
}
}
// Usage:
VStack(spacing: 8) {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
.delayAppearance(by: 0.2)
Text("Hello, world!")
.delayAppearance(by: 0.4)
Button("Let's Begin") {}
.buttonStyle(.borderedProminent)
.delayAppearance(by: 0.5)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment