I need to create Textfield every time i click on button, but when i use foreach to create that, when i write smth. in new textfield it is written also in others. I want that every new textfield will be different that i could write different thing in each of them.
This is what i am using.
@State var arr: [String] = []
@StateObject var homePageVM: HomePageViewModel = HomePageViewModel()
ForEach(arr, id: \.self) { item in
TextField("text", text: item)
}
and in button click
Button {
arr.append($homepageVM.textfieldText)
} label: {
Text("Button")
}
How can i solve this?
CodePudding user response:
struct TextItem: Identifiable {
let id = UUID()
var text: String = ""
}
class Model: ObservableObject {
@Published var textItems: [TextItem] = []
func addTextItem() {
textItems.append(TextItem())
}
// funcs for loading and save model data
}
@StateObject var model = Model()
ForEach($model.textItems) { $item in
TextField("text", text: $item.text)
}
Button("Add") {
model.addTextItem()
}