Reputation: 8376
I have a VStack
where I have a title above some other views. The title is shown/hidden based on the value of an @Published
variable from an environment object. Ideally, when the title should be hidden, I want it to transition by fading out and moving the views below it in the VStack
up. However, what actually happens is it just disappears immediately and moves the rest of the views up without animation. How can I fix this?
struct MyView: View {
@EnvironmentObject var modelController: MyModelController
var body: some View {
VStack {
title()
//..other views here
}
}
@ViewBuilder
func title() -> some View {
if let currentPage = modelController.currentPage,
currentPage >= 6 {
EmptyView()
} else {
Text("Create Event")
}
}
}
Upvotes: 1
Views: 88
Reputation: 257583
Your code snapshot is not testable, but try the following
VStack {
title()
//..other views here
}
.animation(.default, value: modelController.currentPage) // << here !!
Upvotes: 1
Reputation: 19884
You'll need to use the .transition()
modifier to tell the system that you want to animate when the view appears or disappears. Additionally, I don't think you need to return EmptyView
when you want to hide the title.
@ViewBuilder
func title() -> some View {
if modelController.currentPage ?? 0 < 6 {
Text("Create Event")
.transition(.opacity)
}
}
I've used the opacity
transition but it's a very customizable modifier, and you can pass an asymmetric transition that does different animations on insert and removal. I would suggest googling it or looking at the documentation to learn more about it.
Upvotes: 1