Skip to content

Instantly share code, notes, and snippets.

@myurieff
Last active July 24, 2022 14:33
Show Gist options
  • Save myurieff/a545d73e25b0abcebd44b5d33e2818ba to your computer and use it in GitHub Desktop.
Save myurieff/a545d73e25b0abcebd44b5d33e2818ba to your computer and use it in GitHub Desktop.
Counter Transition effect in SwiftUI
import SwiftUI
public extension AnyTransition {
static var carousel: AnyTransition {
.asymmetric(
insertion: .move(edge: .top)
.combined(
with: .modifier(
active: CarouselTransitionModifier(state: .insert),
identity: CarouselTransitionModifier(state: .identity)
)
)
.combined(with: .opacity),
removal: .move(edge: .bottom)
.combined(
with: .modifier(
active: CarouselTransitionModifier(state: .remove),
identity: CarouselTransitionModifier(state: .identity)
)
)
.combined(with: .opacity)
)
}
}
private struct CarouselTransitionModifier: ViewModifier {
enum State {
case insert, identity, remove
}
let state: State
func body(content: Content) -> some View {
var degrees: CGFloat {
switch state {
case .insert: return 16
case .identity: return 0
case .remove: return -16
}
}
return content
.rotation3DEffect(
.degrees(degrees),
axis: (x: 1, y: 0, z: 0)
)
}
}
// Usage:
Text("\(lhsPoints)")
// Tells SwiftUI to treat the view as a new one every
// time the value changes. This will trigger the transition
// effect.
.id("Scoreboard.lhs.\(lhsPoints)")
.transition(.carousel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment