延迟SwiftUI中的过渡 [英] Delay a transition in SwiftUI
问题描述
如何延迟转换?我想单击一个按钮,然后视图应该延迟过渡.
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()
}
}
}
}
}
推荐答案
如果添加显式的id
,它将按您希望的那样工作.请注意,我只进行了一次动画延迟,以使其更加明显.
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()
}
}
}
}
}
我发现显式的id
在大多数情况下都可以帮助我使用过渡.在您的示例中,不使用id
可能导致文本在背景之前更改.这似乎是一个错误,我建议对此提出反馈.
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.
这篇关于延迟SwiftUI中的过渡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!