Home > database >  Toggle a Boolean in a Binding object doesn't update UI
Toggle a Boolean in a Binding object doesn't update UI

Time:06-11

Hello i have an issue with the refresh of my view when i toggle a boolean. Here is the code

class MyItem: Identifiable {
   @Published var isActive: Bool
}

struct myView: View {
   @Binding var item: MyItem
   var body: some View {
      HStack {
         Toggle("", isOn: $item.isActive)
         Spacer()
         TextField("", text: item.isActive ? $text : .constant("")) { isFocused in
             guard !isFocused && text.count == 0 else { return }
             item.isActive.toggle
         }
            .background(item.isActive ? Color.white : Color.clear)
      }
   }
}

when i lose my focus and run item.isActive.toggle it change correctly his value, but my Toggle and my TextField doesn't update their UI (the Toggle is still active and the background of the TextField is still white)

Any idea of what i am missing ?

CodePudding user response:

Binding only updates the view when the wrapped value is updated. However, since your wrapped value is a class, not a struct, the view would only be updated if you replaced the instance with another one, not if you updated a property of the instance.

You need to make MyItem conform to ObservableObject and use @ObservedObject or @StateObject on your view, then it will be updated correctly.

class MyItem: ObservableObject {
   @Published var isActive: Bool
}

struct myView: View {
   @ObservedObject private var item: MyItem

   init(item: MyItem) {
       self.item = item
   }

   var body: some View {
      HStack {
         Toggle("", isOn: $item.isActive)
         Spacer()
         TextField("", text: item.isActive ? $text : .constant("")) { isFocused in
             guard !isFocused && text.count == 0 else { return }
             item.isActive.toggle
         }
            .background(item.isActive ? Color.white : Color.clear)
      }
   }
}
  • Related