首页 > 解决方案 > SwiftUI 中的动画状态变化

问题描述

我目前正在玩 SwiftUI。在 SwiftUI 中,可以为状态更改设置动画,例如:

struct Foo: View {
    @State private var show = false

    var body: some View {
        VStack {
            if show {
                Text("Foo")
            }
            Button(action: {
                withAnimation {
                    self.show.toggle()
                }
            }) {
                Text(show ? "Hide" : "Show")
            }
        }
    }
}

但是,如果我有一个 TextField:

struct Foo: View {
    @State private var text = ""

    var body: some View {
        VStack {
            TextField($text, placeholder: Text("Foo")) {
                print("editing ended")
            }
            if !text.isEmpty {
                Button(action: {}) {
                    Text("Done")
                }
            }
        }
    }
}

我无法找到为这种更改设置动画的方法,因为 TextField 更改了 State 属性,而无需调用 withAnimation()。

是否有可能使这种变化动画化?

标签: swiftanimationtextfieldswiftui

解决方案


只需添加动画修饰符来包装您的按钮

  var body: some View {
    VStack {
      TextField($text, placeholder: Text("Foo")) {
        print("editing ended")
      }
//      if !text.isEmpty {
        Button(action: {}) {
          Text("Done")
        }
        .background(text.isEmpty ? Color.red : Color.yellow )
         //.animation(.basic(duration: 1))
        .animation(Animation.default.speed(1))
      }
    }
  }

推荐阅读