Last active
August 9, 2022 20:28
-
-
Save magnuskahr/ac459b87d48127c46ad785ec259e73d9 to your computer and use it in GitHub Desktop.
SwiftUI Flip transition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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