Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 420
Josef Zoller Avatar asked Jun 08 '19 20:06

Josef Zoller


People also ask

How do you animate when React state changes?

You can use CSS classes to animate in React import React, { useState } from 'react'; import classNames from 'classnames'; import styles from './App. module. css'; const App = () => { const [animate, setAnimate] = useState(false); const handleClick = () => setAnimate(!

How do I animate in SwiftUI?

Change the animation type from easeInOut to spring() . SwiftUI includes basic animations with predefined or custom easing, as well as spring and fluid animations. You can adjust an animation's speed, set a delay before an animation starts, or specify that an animation repeats.


1 Answers

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))
      }
    }
  }
like image 118
DenFav Avatar answered Sep 30 '22 18:09

DenFav