Skip to content

Instantly share code, notes, and snippets.

@shaundon
Created February 21, 2023 20:30
Show Gist options
  • Save shaundon/0fd42328a6952112eb614407241bd6fb to your computer and use it in GitHub Desktop.
Save shaundon/0fd42328a6952112eb614407241bd6fb to your computer and use it in GitHub Desktop.
A SwiftUI transition for making views fall off the screen with a slight rotation effect.
struct FallWithRotationModifier: ViewModifier {
let isHidden: Bool
var yOffset: CGFloat {
return isHidden ? 1000 : 0
}
var rotationDegrees: Double {
guard isHidden else { return 0 }
let degrees = Double.random(in: 30...90)
return Bool.random() ? degrees : -degrees
}
// Randomly lean to the left or right when falling.
var anchor: UnitPoint {
return Bool.random() ? .bottomLeading : .bottomTrailing
}
// Slowly fade out while transitioning.
var opacity: Double {
return isHidden ? 0 : 1
}
func body(content: Content) -> some View {
content
.rotationEffect(.degrees(rotationDegrees), anchor: anchor)
.offset(x: 0, y: yOffset)
.opacity(opacity)
}
}
extension AnyTransition {
static var fallOffscreenWithRotation: AnyTransition {
.modifier(
active: FallWithRotationModifier(isHidden: true),
identity: FallWithRotationModifier(isHidden: false)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment