SwiftUI Lists & Forms
SwiftUI Lists & Forms
Build data-driven lists with List and collect inputs with Form, rows, and controls.
Lists
Render collections with List and ForEach using identifiable items.
Syntax:
List(items) { Text($0.title) }- or
List { ForEach(items) { ... } }
Example
import SwiftUI
struct Todo: Identifiable { let id: Int; let title: String }
struct TodoList: View {
let items = [Todo(id: 1, title: "Buy milk"), Todo(id: 2, title: "Walk dog")]
var body: some View {
List(items) { t in Text(t.title) }
}
}
import SwiftUI
struct ContentView: View {
var body: some View { TodoList() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
This example displays a simple list of identifiable items using List.
Forms
Group input controls using Form and built-in rows.
Syntax: Form { Section { TextField(...) } Toggle(...) Stepper(...) }
Example
import SwiftUI
struct SettingsForm: View {
@State private var name = ""
@State private var notifications = true
@State private var count = 1
var body: some View {
Form {
Section(header: Text("Profile")) {
TextField("Name", text: $name)
}
Section(header: Text("Preferences")) {
Toggle("Notifications", isOn: $notifications)
Stepper("Count: \(count)", value: $count, in: 1...10)
}
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View { SettingsForm() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
This example collects inputs using a text field, toggle, and stepper arranged in a form with sections.
Tip: Use ForEach inside lists for dynamic content and identifiable items.