SwiftUI height animation of a text frame when @ObservedObject change

552 views Asked by At

I try to make a smooth animation when the NetStatus change but it's not working like i want.

I want to get the same effect as when i press the button with the toggle animation. The commented button animation is working great and i try to replicate it with the scaling of the height of the text frame.

The commented button code is just for a working example of the animation effect that i want (expand and close gracefully), i don't need this code.

How can i do that?

import SwiftUI

struct NoNetwork: View {
  let screenSize: CGRect = UIScreen.main.bounds
  
  @ObservedObject var online = NetStatus()
  
  var body: some View {
    
    VStack{
      Text("NoNetworkTitle")
        .fontWeight(.bold)
        .foregroundColor(Color.white)
        .frame(width: screenSize.width, height: self.online.connected ? 0 : 40, alignment: .center)
        // .animation(.easeIn(duration: 5))
        .background(Color.red)
      
//      Button(action: {
//        withAnimation {
//          self.online.connected.toggle()
//        }
//      }, label: {
//        Text("Animate")
//      })
      
    }
  }
}

struct NoNetwork_Previews: PreviewProvider {
  static var previews: some View {
    NoNetwork()
  }
}

1

There are 1 answers

0
vacawama On

To animate when online.connected changes, put the .animation modifier on the VStack:

VStack{
  Text("NoNetworkTitle")
    .fontWeight(.bold)
    .foregroundColor(Color.white)
    .frame(width: screenSize.width, height: self.online.connected ? 0 : 40, alignment: .center)
    .background(Color.red)
  
  Button(action: {
      self.online.connected.toggle()
  }, label: {
    Text("Animate")
  })
  
}
.animation(.easeInOut(duration: 0.5))

This will animate the other views in the VStack as the Text appears and disappears.