- Regular animations render the objects on the screen already.
- If we have an object that isn’t on the screen, we use transition.
- Required conditional logics to use transition.
- Due to that transition is under utilized.
1. Create a button and a rounded rectangle with half-height of canvas size.
- We will use GeometryReader to make it half-canvas size.
- Wrap the content with
GeometryReader{ geometry in …}
- Set the height with
geometry.size.height * 0.5
- Wrap the content with
import SwiftUI
struct TransitionView: View {
var body: some View {
VStack{
GeometryReader{ geometry in
HStack{
Spacer()
RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/25.0/*@END_MENU_TOKEN@*/)
.frame(width: 100, height: geometry.size.height * 0.5)
Spacer()
}
}
Button("Button"){
print("Hello")
}
}.padding().glassBackgroundEffect()
}
}
#Preview {
TransitionView()
}
2. Add a animation
- Add a boolean variable.
- use @State to create a boolean
- Add withAnimation function in button.
withAnimation(Animation.default){boolean.toggle()}
- add boolean to see the animation.
import SwiftUI
struct TransitionView: View {
@State var isAnimating: Bool = false
var body: some View {
VStack{
GeometryReader{ geometry in
HStack{
Spacer()
RoundedRectangle(cornerRadius:25.0)
.frame(width: 100, height: geometry.size.height * 0.5)
.opacity(isAnimating ? 0.1 : 1.0)
Spacer()
}
}
Button("Button"){
withAnimation(Animation.default){
isAnimating.toggle()
}
}
}.padding().glassBackgroundEffect()
}
}
3. Change the opacity animation to opacity transition.’
- We wrap the rounded rectangle with if Statement
- add
.transition(.opacity)
instead of.opacity
var body: some View {
VStack{
GeometryReader{ geometry in
HStack{
Spacer()
if isAnimating {
RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/25.0/*@END_MENU_TOKEN@*/)
.frame(width: 100, height: geometry.size.height * 0.5)
.transition(.slide)
}
Spacer()
}
}
Button("Button"){
withAnimation(Animation.default){
isAnimating.toggle()
}
}
}.padding().glassBackgroundEffect()
}
}
❓
List of transitions to use
// .transition(.scale)
// .transition(.slide)
// .transition(.move(edge: .top))
// .transition(.opacity)
4. We can customize the transition animation by using AnyTransition
- instead of
.opacity
, we can wrap it withAnytransition.opacity.animation(.easeIn(duration: 1))
if isAnimating {
RoundedRectangle(cornerRadius:)
.frame(width: 100, height: geometry.size.height * 0.5)
.transition(AnyTransition.slide.animation(.easeIn(duration: 1)))
}
5. We can add a entering and exiting transition.
- use
.asymmetric
.transition(.asymmetric(
insertion: AnyTransition.opacity.animation(.easeIn(duration: 1)),
removal: AnyTransition.scale.animation(.easeOut(duration: 1 + 1))
))
Use .transition to animate an object's entry and exit.
❓When should we use .animation and .transition?
💛 Playing with the .asymmetric transition effect can be fun.
🫥 So, which one do we use the most?
#visionOS #applevisionpro #swiftUI #appdevelopment