'Changing SwiftUI TextField Values Programmatically

I have SwiftUI textfield. I submit same values and process these values in an other class. According to process in this class I have to replace values in textField with previous data programmatically.

As usual this a pain in swiftUI. How can I do it ?



Solution 1:[1]

Why it have to be pain. In UIView textField.text = "" was enough. I am sure they have their reasons above my grasp.

But while using SwiftUI I did it like that first you put your variables in

class Shared: ObservableObject {
static let shared = Shared()

@Published var texEditsDefaults = Edits().defaultValues

}

then in process class

 class Calculation {

 @ObservedObject var calculation = Shared.shared


   // do something

   texEditsDefaults = newValues

 }

and

struct TextValuesView: View {
  @ObservedObject var calculation = Shared.shared
   var body: some View {
    ForEach(0..<calcNames.count, id: \.self) { calcIndex in               
      TextField(calcNames[calcIndex], text: $calculation.texEditsDefaults[calcIndex])
         .onSubmit{                                     
           // send values class calculation
         }
       }      
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1