2

我想在 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()
    }
}
4

2 回答 2

1

有两种可能

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

于 2020-11-18T13:30:06.697 回答
0

我现在想将它与 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)
        }
    }
}

}

于 2020-11-20T16:56:52.780 回答