I have a SwiftUI View
which has a custom animation that runs onAppear
. I am trying to get the view to animate onDisappear
too but it just immediately vanishes.
The below example reproduces the problem - the MyText
view should slide in from the left and slide out to the right. The id
modifier is used to ensure a new view is rendered each time the value changes, and I have confirmed that both onAppear
and onDisappear
are indeed called each time, but the animation onDisappear
never visibly runs. How can I achieve this?
struct Survey: View {
@State private var id = 0
var body: some View {
VStack {
MyText(text: "\(id)").id(id)
Button("Increment") {
self.id += 1
}
}
}
struct MyText: View {
@State private var offset: CGFloat = -100
let text: String
var body: some View {
return Text(text)
.offset(x: offset)
.onAppear() {
withAnimation(.easeInOut(duration: 2)) {
self.offset = 0
}
}
.onDisappear() {
withAnimation(.easeInOut(duration: 2)) {
self.offset = 100
}
}
}
}
}