Animate State change in SwiftUI

Jos*_*ler 1 animation textfield swift swiftui

I‘m currently playing around with SwiftUI. In SwiftUI it‘s possible, to animate a State change for example like so:

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")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

But if I have for example a 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")
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

I‘m not able to find a way to animate this change, because the State property is changed by the TextField without a call to withAnimation().

Is it possible to get this change animated?

mal*_*hal 7

TextField("Placeholder", text:$text.animation())

当文本发生变化时,所有使用文本的内容都会被动画化。


Den*_*Fav 5

只需添加动画修饰符即可包装按钮

  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))
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

  • 好的。我试过了,但不幸的是它只会在 Button 中淡出,但会立即将其删除。可能是错误?我还尝试了一些修饰符更改,例如按钮上的`.foregroundColor(text.isEmpty ? .red : .green)`,而不是if,但这也没有动画。 (2认同)