为什么文本出现在加载动画?

Why the text appear at loading with animation?

我想在 NavigationBarTitle 后面隐藏一些文本并在用户按下按钮时显示它,它工作正常。唯一的问题是动画。在加载时,我们看到文本在 NavigationBarTitle 后面移动,这不是我想要的。

我该如何解决这个问题?

我尝试了偏移量和位置,但它不起作用...

代码:

import SwiftUI

struct TestZStackNavigationView: View {
    @State var isShowed = false
    let screenSize: CGRect = UIScreen.main.bounds
    
    var body: some View {
        NavigationView {
            VStack(alignment: .center, spacing: 0){
                Text("Im the hidden text")
                    .fontWeight(.bold)
                    .foregroundColor(Color.white)
                    .frame(width: screenSize.width, height: 40, alignment: .center)
                    .background(Color.red)
//                    .offset(y: self.isShowed ? -315 : -355)
                    .position(x: screenSize.width / 2, y: self.isShowed ? 20 : -40)
                    .animation(.easeIn(duration: 0.5))

                Button(action: {
                    self.isShowed.toggle()
                }) {
                    Text("click me")
                }
                .navigationBarTitle(Text("Navigation Bar Title"), displayMode:.inline)
            }
        }
    }
}

struct TestZStackNavigationView_Previews: PreviewProvider {
    static var previews: some View {
        TestZStackNavigationView()
    }
}

有两种可能

  1. 为每个状态制作动画(并且没有其他更改)
    .animation(.easeIn(duration: 0.5), value: isShowed)
  1. 将隐式动画替换为修饰符并在动作中添加显式动画
        .position(x: screenSize.width / 2, y: self.isShowed ? 20 : -40)
    //    .animation(.easeIn(duration: 0.5)) // remove from here

    Button(action: {
      withAnimation(Animation.easeIn(duration: 0.5)) {   // << add this
        self.isShowed.toggle()
      }
    }) {
        Text("click me")
    }

我现在想将它与 ObservedObject 一起使用,但我得到了与第一个代码相同的行为。为什么?

struct TestZStackNavigationView: View {
//    @State var isShowed = false
let screenSize: CGRect = UIScreen.main.bounds

@ObservedObject var online = NetStatus()

var body: some View {
    NavigationView {
        VStack(alignment: .center, spacing: 0){
            Text("Im the hidden text")
                .fontWeight(.bold)
                .foregroundColor(Color.white)
                .frame(width: screenSize.width, height: 40, alignment: .center)
                .background(Color.red)
                .position(x: screenSize.width / 2, y: online.connected ? -40 : 20)
                .animation(.easeIn(duration: 0.5), value: online.connected)
                .navigationBarTitle(Text("Navigation Bar Title"), displayMode:.inline)
        }
    }
}

}