在 SwiftUI 中延迟转换

sim*_*bac 5 animation swift swiftui

如何延迟过渡?我想单击一个按钮,然后视图应该延迟转换。

我有以下代码,但没有正确同步。

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()
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ars*_*ius 7

如果您添加显式,id它会按您的意愿工作。请注意,我只做了一个动画延迟,以使其更明显地表明这是有效的。

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()
                }
            }
        }
    }
}

Run Code Online (Sandbox Code Playgroud)

我发现id在我想使用过渡的大部分时间里,显式是有帮助的。在您的示例中,不使用id可能会导致文本在背景之前发生变化。这似乎是一个错误,我建议提交有关它的反馈。