skip to Main Content

Im trying to adapt the animation to my rectangle, I just don’t know how.
I got in my view a rectangle that appears when the screen shows up and I got this warning:
‘animation’ was deprecated in iOS 15.0: Use withAnimation or animation(_:value:) instead.

Rectangle()
     .animation(.easeInOut(duration: 0.6))
     .foregroundColor(.green)
     .frame(width: 20, height: max(10, alturas.0))
     .cornerRadius(6)

I tried like this

Rectangle()
     .foregroundColor(.green)
     .frame(width: 20, height: max(10, alturas.0))
     .cornerRadius(6)
     .onAppear{
          withAnimation{
               .easeInOut(duration: 0.6)
          }
     }

2

Answers


  1. You need to apply the new values within the withAnimation block to expect those changes to be animated. For instance like this:

    @State private var rectangleWidth: CGFloat = 0
    
    var body: some View {
        Rectangle()
            .foregroundColor(.green)
            .frame(width: rectangleWidth, height: rectangleWidth)
            .cornerRadius(6)
            .onAppear(perform: {
                withAnimation {
                    rectangleWidth = 20
                }
            })
    }
    

    This will make the rectangle start with size (0, 0) and once it appears it will increase its size to (20, 20).

    Login or Signup to reply.
  2. It seems that you are controlling the animation using a tuple. Maybe it is defined something like this:

    typealias Alturas = (CGFloat, CGFloat)
    @State private var alturas: Alturas = (0, 0)
    

    So to get rid of the deprecation warning, you just need to add value as a parameter to the .animation modifier, like this:

    Rectangle()
        .animation(.easeInOut(duration: 0.6), value: alturas.0)
        // other modifiers as before
    

    Alternatively, you can remove the .animation modifier completely and perform the update withAnimation, like this:

    Rectangle()
        .foregroundColor(.green)
        .frame(width: 20, height: max(10, alturas.0))
        .cornerRadius(6)
        .onAppear {
            withAnimation(.easeInOut(duration: 6)) {
                alturas.0 = 100
            }
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search