royB
royB

Reputation: 12977

referenced binding param not triggering animation

I have a custom view

struct CustomView: View {

  @Binding var text: String
  ...

var body: some View {
  VStack {
    ...
    Text(SomeText)
      .offset(y: text.isEmpty ? 0 : -25)
      .scaleEffect(text.isEmpty ? 1 : 0.5, anchor: .leading)
      .animation(.spring(), value: text.isEmpty)

    ...
  }

the scale effect and offset animation never trigger if text is referenced from an object.

For example, I have a ViewModel such as

class SomeViewModel: ObservableObject {
  @Published var text: String = ""
}

And the parent View such as

struct ParentView: View {
  @State private var vm = SomeViewModel()
  
  @State private var text = "" //this one works!
   ...
  
   var body: some View {
     ...
     CustomView(..., text: $vm.text) // no animation, but the value of v.name is updated
     CustomView(..., text: $text)) // everything works, including animation

Upvotes: 0

Views: 20

Answers (1)

kuncan
kuncan

Reputation: 76

For SwiftUI to properly update based on changes of an ObservableObject, you will need to use a different property wrapper. Usually this is either @ObservedObject or @StateObject dependent on the context you are using it in.

Try using @StateObject if this is where you are first initialising the class.

StateObject Documentation

Upvotes: 1

Related Questions