Delay a transition in SwiftUI

这一生的挚爱 提交于 2020-07-21 07:52:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!