Josef Zoller
Josef Zoller

Reputation: 951

Animate State change in 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")
            }
        }
    }
}

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

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?

Upvotes: 16

Views: 14902

Answers (2)

malhal
malhal

Reputation: 30617

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

Everything that uses the text will be animated when it is changed.

Upvotes: 8

DenFav
DenFav

Reputation: 2811

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

Upvotes: 14

Related Questions