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

Demo.swift

ContentView.swift

App.swift

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) }
} }

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

Demo.swift

ContentView.swift

App.swift

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)
  }
}
} }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *