Your code wouldn't compile as-is, but I think you want your GradientLegendView to slide in from the leading edge, and out on the trailing edge of the ContentView, in response to pressing a button. And you don't want to animate the isShowingLegend variable, you'd rather attach the animation to your GradientLegendView.
The thing is, what you want to animate (the position of the GradientLegendView) isn't intrinsic to the GradientLegendView. The view position is a property of the GradientLegendView which only makes sense in the ContentView.
I took the .transition modifier out of the GradientLegendView, and removed its isShowingLegend. The GradientLegendView is the thing which shows the gradient legend; it doesn't make sense for it to take that bool parameter. The piece of UI which uses the GradientLegendView decides whether to show it or not.
I attached a .transition(.slide) to the HStack which builds your GradientLegendView, and provided a .animation controlled by isShowingLegend. The animation is applied to a Group in your overlay. The Group returns an HStack if isShowingLegend is true and an (implied) EmptyView otherwise. It is necessary because the type of the parameter to .overlay should be some View.
this is my ContentView
@State private var isShowingLegend = true
var body: some View {
Button("Press Me") {
isShowingLegend.toggle()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
// .task {
// setupMenuItems() // won't compile, don't have
// }
.overlay(
Group {
if isShowingLegend {
HStack {
GradientLegendView(
// doesn't need isShowingLegend
labels: SampleData.createHeatmapLegendLabelArray(),
colors: SampleData.createHeatmapLegendColorArray(),
width: 120,
height: 200)
Spacer()
}
.transition(.slide)
}
}
.animation(.easeInOut, value:isShowingLegend)
,
alignment: .bottom
)
}
}
I don't know if this is what you are looking for (or were looking for, because it has been two weeks!), but I hope it helps.
This is a pretty good article about transitions https://www.objc.io/blog/2022/04/14/transitions/
And I found this tutorial very useful also https://www.hackingwithswift.com/books/ios-swiftui/creating-implicit-animations
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: