My issue is that my SportMenu
animates in, as desired, when a button is pressed (and an observed value is toggled) from Home
view, but does not animate out, when that same value is toggled from SportMenu
. Anyone know why? I want the SportMenu
to animate out as a reverse of how it comes in.
Here are the relevant files:
// ContentView.swift
class SportMenuStatus: ObservableObject {
@Published var isSportMenuShowing = false
func toggleMenu() {
if isSportMenuShowing == true {
isSportMenuShowing = false
} else {
isSportMenuShowing = true
}
}
}
struct ContentView: View {
@State private var tab = 0
@StateObject var isSportMenuShowing = SportMenuStatus()
var body: some View {
VStack {
ZStack {
TabView(selection: $tab) {
Group {
Home(isSportMenuShowing: isSportMenuShowing)
// More code I don't think is relevant
The first tab loads up the Home
view which has a button in:
// Home.swift
struct Home: View {
@ObservedObject var isSportMenuShowing: SportMenuStatus
var body: some View {
VStack {
ZStack {
Image("home")
.resizable()
.aspectRatio(contentMode: .fill)
// The Menu button
HStack {
VStack {
Group {
Button(action: {
withAnimation {
isSportMenuShowing.toggleMenu()
}
}) {
Color(.red)
}.frame(width: 200, height: 45)
.opacity(0.6)
}
Spacer()
}
Spacer()
}
.offset(x: 10, y: 60)
let _ = print(isSportMenuShowing.isSportMenuShowing)
if isSportMenuShowing.isSportMenuShowing {
SportMenu(isSportMenuShowing: isSportMenuShowing).transition(
.asymmetric(
insertion: .move(edge: .top),
removal: .move(edge: .bottom)
)
)
}
}
Spacer()
}
}
}
When that button is clicked, it toggles the Bool in the ContentView
which flows the value back into Home and shows the SportMenu()
view:
// SportMenu
struct SportMenu: View {
@ObservedObject var isSportMenuShowing: SportMenuStatus
var body: some View {
VStack {
ZStack {
Image("sportmenu-no-cross")
.resizable()
.aspectRatio(contentMode: .fill)
// Close icon
VStack {
HStack {
Spacer()
ZStack {
Image("close")
Button(action: {
withAnimation {
isSportMenuShowing.toggleMenu()
}
}) {
Color.red.opacity(0.5)
}
.frame(width: 50, height: 50)
}
}
Spacer()
}
.offset(x: -20, y: 60)
}
}
.edgesIgnoringSafeArea(.top)
}
}
However, when I click the button in the SportMenu to toggle the value back to false, the SportMenu
instantly disappears instead of animating.
How can I get the SportMenu to animate in and out when that value is toggled?