SwiftUI - Add Records to a Dynamic List
Here is an example of how to create a form that will adds records to a list dynamically.
Content View
struct ContentView: View {
@State private var title = String()
@State private var name = String()
@State private var people: [Person]? = nil
@State private var showAddField: Bool = false
var body: some View {
Form {
List {
if let unwrappedPeople = people {
ForEach(unwrappedPeople, id: \.id) { person in
HStack {
Text(person.title)
Spacer()
Text(person.name)
}
}
} else {
EmptyView()
}
if showAddField {
Button(action: addRow) {
HStack {
Spacer()
Text("Add Row")
Spacer()
}
}
} else {
HStack(alignment: .center) {
TextField("Title", text: $title)
TextField("Name", text: $name)
HStack {
Button(action: { <br>
self.submit(title: self.title, name: self.name)
}) {
Text("Submit")
}
.buttonStyle(BorderlessButtonStyle())
}
}
}
}
}
}
}
Person Structure
struct Person: Identifiable {
let id = UUID()
var title: String
var name: String
}
Add Row and Submit Functions
private func addRow() {
self.showAddField = false
}
private func submit(title: String, name: String) {
if self.people?.isEmpty == nil {
self.people = [Person(title: self.title, name: self.name)]
} else {
self.people?.append(Person(title: self.title, name: self.name)]
}
self.title = String()
self.name = String()
self.showAddField = true
}