问题
How can I delay a transition? I want to click on a button and then a view should transition with a delay.
I have the following code but it is not properly synchronized.
struct ContentView: View {
@State var showOne = true
var body:some View{
VStack{
if showOne{
HStack{
Spacer()
Text("One")
Spacer()
}
.animation(Animation.default.delay(2))
.background(Color.red)
.transition(.slide)
}else{
HStack{
Spacer()
Text("Two")
Spacer()
}
.background(Color.blue)
.animation(Animation.default.delay(1))
.transition(.slide)
}
Button("Toggle"){
withAnimation(){
self.showOne.toggle()
}
}
}
}
}
回答1:
If you add an explicit id
it works as you would like. Note, I made only one animation delay to make it a little more obvious that this is working.
struct ContentView: View {
@State var showOne = true
var body:some View {
VStack {
if showOne {
HStack {
Spacer()
Text("One")
Spacer()
}
.background(Color.red)
.id("one")
.animation(Animation.default)
.transition(.slide)
} else {
HStack {
Spacer()
Text("Two")
Spacer()
}
.background(Color.blue)
.id("two")
.animation(Animation.default.delay(2))
.transition(.slide)
}
Button("Toggle") {
withAnimation {
self.showOne.toggle()
}
}
}
}
}
I've found an explicit id
to be helpful most of the time I want to use a transition. In your example, not using the id
can cause the text to change before the background. This would seem to be a bug, and I recommend filing feedback on it.
来源:https://stackoverflow.com/questions/60271061/delay-a-transition-in-swiftui