SwiftUI Lists & Forms

SwiftUI Lists and Forms

Almost every app requires displaying scrollable rows of data or capturing user input through settings screens.

SwiftUI makes creating these robust layouts incredibly fast using the List and Form views.


Creating a List

A List in SwiftUI is the equivalent of a UITableView in UIKit, but vastly simpler to implement.

You can create a static list by just placing views directly inside the List block.

Static List:

import SwiftUI

struct SettingsList: View { var body: some View { List { Text("Profile") Text("Notifications") Text("Privacy") } } }


Dynamic Lists with ForEach

Usually, you want to build a list from an array of data.

To do this, you pass your array to the List, but the data type must conform to the Identifiable protocol so SwiftUI knows how to track each row uniquely.

Dynamic List:

// The model must conform to Identifiable
struct Task: Identifiable {
    let id = UUID()
    let name: String
}

struct TaskListView: View { let tasks = [ Task(name: "Buy groceries"), Task(name: "Walk the dog"), Task(name: "Learn SwiftUI") ] var body: some View { // SwiftUI automatically creates a row for each task! List(tasks) { task in Text(task.name) } } }


Using Forms

A Form is a specialized type of List designed specifically for data entry controls like toggles, text fields, and pickers.

Forms automatically adapt their styling based on the platform, providing that classic iOS "Settings app" look.

You can organize your forms beautifully using Section blocks.

Form Example:

struct SettingsForm: View {
    @State private var notificationsEnabled = true
    @State private var username = ""
    var body: some View {
        Form {
            Section(header: Text("Profile")) {
                TextField("Username", text: $username)
            }
            Section(header: Text("Preferences")) {
                Toggle("Enable Notifications", isOn: $notificationsEnabled)
            }
        }
    }
}

Exercise

What protocol must your custom data structs conform to in order to be used directly in a dynamic SwiftUI List?