iOS
SwiftUI - 애니메이션 사라질 때 동작하지 않는 경우(SwiftUI Disappear transition not animated)
Hey_Hen
2022. 5. 10. 23:29
문제
SwiftUI는 withAnimation으로 간단하게 애니메이션을 할 수 있는데, 종종 사라질 때 이 애니메이션이 작용하지 않는 듯한 모습을 보입니다.
Tap을 하면 Circle은 자연스럽게 opacity Transition이 동작하는데, 글자는 나타날 때는 애니메이션이 잘 되는거 같은데, 사라질 때는 애니메이션이 동작하지 않는 것 처럼 뿅하고 사라집니다.
더보기
struct ContentView: View {
@State var state: Bool = false
var body: some View {
VStack {
Button {
withAnimation {
state.toggle()
}
} label: {
Text("Tap \(state ? "On" : "Off")")
}
ZStack {
Circle()
.foregroundColor(state ? .blue : .clear)
if state {
Text("Hello Swift")
.foregroundColor(state ? .white : .black)
.font(.system(size: 55))
.transition(.opacity.animation(.easeIn(duration: 1).delay(0.5)))
}
}
}
}
}
애니메이션이 되지 않는 것일까요?
아래 백그라운드에 Rectable을 검게 반만 깔아보았습니다. 검은 배경이 있는 곳은 애니메이션이 정상적으로 보이는데
하얀 배경쪽에서는 바로 사라지는 것 처럼 보입니다.
원인
원인은 ZIndex로 Text가 Transition 될 때 ZIndex가 원 보다 아래로 내려가면서 한번에 사라지는 것 처럼 보입니다. 아마 이는 명백한 버그 일 것입니다..
해결
해결법은 간단한데, Text가 Transition 될 때 강제로 ZIndex가 0이 되는 것이 문제이므로, ZIndex를 명시적으로 1로 정하거나 원의 ZIndex를 0보다 낮은 -1 등으로 정하면 해결 할 수 있습니다.
struct ContentView: View {
@State var state: Bool = false
var body: some View {
VStack {
Button {
withAnimation {
state.toggle()
}
} label: {
Text("Tap \(state ? "On" : "Off")")
}
ZStack {
Circle()
.foregroundColor(state ? .blue : .clear)
if state {
Text("Hello Swift")
.foregroundColor(state ? .white : .black)
.font(.system(size: 55))
.zIndex(1)
}
}
.background(Rectangle().foregroundColor(.black).frame(width: UIScreen.main.bounds.width / 2), alignment: .leading)
}
}
}
참고
https://sarunw.com/posts/how-to-fix-zstack-transition-animation-in-swiftui/
https://stackoverflow.com/questions/57730074/transition-animation-not-working-in-swiftui