I want to create a certain amount of TextFields on a view based on the number the user inputs. For Example, if the user inputs 5 I would like to display 5 TextFields on the view. I was thinking about using "Form" with a "For Each," but I cant figure out the correct syntax or if it's possible at all. This is my code so far:
struct NameView: View{
@Binding var numNames: String
@State private var newSet = []
var body: some View{
var numNameInt = Int(numNames)
Form{
ForEach(newSet) { index in
TextField("Name", text: $newSet[index])
}
}
}
Any help would be appreciated.
The only limitation to the following approach is that you need to know the maximum number of names someone is able to have. This makes sense, because you wouldn't want someone to make infinite names and crash your app, but unless there's a way to dynamically create bindable variables, you have to have a limit of how many names they might have.
The example below accounts for a limit of 3 names, hence the name1
, name2
, and name3
variables
struct NameView: View {
@State var numNames: String = ""
@State var name1: String = ""
@State var name2: String = ""
@State var name3: String = ""
@State var nameArray: [String] = []
var body: some View {
VStack {
TextField(text: $numNames) {} //Accepts the number of names they have
if let num = Int(numNames) { //If they input an int...
ForEach(0..<num, id: \.self) { n in // then iterate for each one
TextField(text: $nameArray[n]) {} //and make a textfield to the corresponding variable
}
}
}
.onAppear {
self.nameArray = [name1, name2, name3]
}
}
}
Later on, you could turn the array into an array of only the names that they actually have by doing nameArray = nameArray.filter { $0 != "" }