Skip to content

Instantly share code, notes, and snippets.

@magnuskahr
Last active August 9, 2022 20:28
Show Gist options
  • Save magnuskahr/ac459b87d48127c46ad785ec259e73d9 to your computer and use it in GitHub Desktop.
Save magnuskahr/ac459b87d48127c46ad785ec259e73d9 to your computer and use it in GitHub Desktop.
SwiftUI Flip transition
extension AnyTransition {
static var flip: AnyTransition {
.modifier(
active: FlipEffect(flip: .active, animatableData: 1),
identity: FlipEffect(flip: .identity, animatableData: 0)
)
}
}
private struct FlipEffect: GeometryEffect {
enum Flip {
case active, identity
}
let flip: Flip
var animatableData: Double
func effectValue(size: CGSize) -> ProjectionTransform {
var rotate = CATransform3DIdentity
rotate.m34 = -1 / max(size.width, size.height)
rotate = CATransform3DRotate(rotate, Angle(degrees: 180).radians * rotation, 1, 0, 0)
rotate = CATransform3DTranslate(rotate, size.width / -2, size.height / -2, 0)
let translate = CGAffineTransform(
translationX: size.width / 2,
y: size.height / 2
)
return .init(rotate).concatenating(.init(translate))
}
private var rotation: Double {
switch flip {
case .active: return animatableData <= 0.5 ? animatableData : 0.5
case .identity: return animatableData < 0.5 ? -animatableData : 0.5
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment