过渡动画在SwiftUI中不起作用 [英] Transition animation not working in SwiftUI

查看:191
本文介绍了过渡动画在SwiftUI中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个非常简单的过渡动画,该动画可以通过点击按钮在屏幕中央显示/隐藏消息:

I'm trying to create a really simple transition animation that shows/hides a message in the center of the screen by tapping on a button:

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

    var body: some View {
        ZStack {
            Color.yellow

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

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

根据 .transition(.opacity)动画


插入时从透明过渡到不透明,移除后从不透明
过渡到透明。

A transition from transparent to opaque on insertion, and from opaque to transparent on removal.

showMessage 状态属性变为true时,消息应淡入,而变为false时,消息应淡出。就我而言,这是不正确的。该消息以淡入淡出的动画显示,但它完全没有动画隐藏。有任何想法吗?

the message should fade in when the showMessage state property becomes true and fade out when it becomes false. This is not true in my case. The message shows up with a fade animation, but it hides with no animation at all. Any ideas?

编辑:查看下面的gif结果,该结果来自模拟器。

See the result in the gif below taken from the simulator.

推荐答案

问题是,当视图来来往往时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)
        }
    }
}

}

这篇关于过渡动画在SwiftUI中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆