Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Requested
Considered
19 occasions
I attempt to swap from one display screen to a different by urgent a button (see full code beneath). The swap from the primary view to the second view (and vice versa) works, however no animation is going down.
Why does this conduct occur?
Full code:
struct ContentView: View {
@AppStorage("firstViewActive") var isFirstViewActive: Bool = true
var physique: some View {
if isFirstViewActive {
FirstView()
} else {
SecondView()
}
}
}
struct FirstView: View {
@AppStorage("firstViewActive") var isFirstViewActive: Bool = true
var physique: some View {
ZStack {
Colour(.purple).ignoresSafeArea(.all, edges: .all)
VStack {
Spacer()
Textual content("That is the primary view")
Spacer()
Button {
withAnimation {
isFirstViewActive = false
}
} label: {
Textual content("Go to second view")
}
Spacer()
}
}
}
}
struct SecondView: View {
@AppStorage("firstViewActive") var isFirstViewActive: Bool = false
var physique: some View {
ZStack {
Colour(.blue).ignoresSafeArea(.all, edges: .all)
VStack {
Spacer()
Textual content("That is the second view")
Spacer()
Button {
withAnimation {
isFirstViewActive = true
}
} label: {
Textual content("Go to first view")
}
Spacer()
}
}
}
}
1
The withAnimation
perform works for views which can be tailored a way, as an instance their opacity or measurement. In your case you do not adapt one view, however you turn between two views. You must add a transition
modifier. (Transitions are particular animations for views, that come or go from their father or mother view).
So attempt:
var physique: some View {
if isFirstViewActive {
FirstView()
.transition(.slide)
} else {
SecondView()
.transition(.opacity)
}
}
2
The issue is with
@AppStorage("firstViewActive") var isFirstViewActive: Bool = true
In case you change that to
@State var isFirstViewActive: Bool = true
and use @Binding
in subviews, you’ll get the default animations.
In iOS 16, there appears to be an issue with @AppStorage
vars and animation. However you possibly can confer with this workaround
lang-swift