简体   繁体   English

SwiftUI 中的动画状态更改

[英]Animate State change in SwiftUI

I'm currently playing around with SwiftUI.我目前正在玩 SwiftUI。 In SwiftUI it's possible, to animate a State change for example like so:在 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")
            }
        }
    }
}

But if I have for example a TextField:但是,如果我有一个 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")
                }
            }
        }
    }
}

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().我无法找到一种方法来为这种更改设置动画,因为 TextField 更改了 State 属性,而无需调用 withAnimation()。

Is it possible to get this change animated?是否可以将这种更改动画化?

Just add the animation modifier to wrap your button只需添加动画修饰符来包裹你的按钮

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

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

使用文本的所有内容都将在更改时进行动画处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM