且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

过渡动画在 SwiftUI 中不起作用

更新时间:2023-01-08 17:13:31

问题是当视图在 ZStack 中来来去去时,它们的zIndex"不会保持不变.发生的事情是,当showMessage"从 true 变为 false 时,带有Hello World"文本的 VStack 被放在堆栈的底部,并且黄色立即绘制在它的顶部.它实际上正在淡出,但它在黄色后面这样做,所以你看不到它.

The problem is that when views come and go in a ZStack, their "zIndex" doesn't stay the same. What is happening is that the when "showMessage" goes from true to false, the VStack with the "Hello World" text is put at the bottom of the stack and the yellow color is immediately drawn over top of it. It is actually fading out but it's doing so behind the yellow color so you can't see it.

要修复它,您需要为堆栈中的每个视图明确指定zIndex",以便它们始终保持不变 - 就像这样:

To fix it you need to explicitly specify the "zIndex" for each view in the stack so they always stay the same - like so:

struct ContentView: View {
@State private var showMessage = false

var body: some View {
    ZStack {
        Color.yellow.zIndex(0)

        VStack {
            Spacer()
            Button(action: {
                withAnimation(.easeOut(duration: 3)) {
                    self.showMessage.toggle()
                }
            }) {
                Text("SHOW MESSAGE")
            }
        }.zIndex(1)

        if showMessage {
            Text("HELLO WORLD!")
                .transition(.opacity)
                .zIndex(2)
        }
    }
}

}