0
0
iOS Swiftmobile~5 mins

List view basics in iOS Swift

Choose your learning style9 modes available
Introduction

A list view shows many items in a scrollable column. It helps users see and pick from multiple things easily.

Showing a list of contacts in a phone app.
Displaying messages in a chat app.
Listing songs in a music player.
Showing tasks in a to-do list app.
Displaying settings options in an app.
Syntax
iOS Swift
import SwiftUI

struct ContentView: View {
  let items = ["Apple", "Banana", "Cherry"]

  var body: some View {
    List(items, id: \.self) { item in
      Text(item)
    }
  }
}

The List view creates a scrollable list of rows.

Use id: \.self when your data items are simple and identifiable by themselves.

Examples
A simple list of color names.
iOS Swift
List(["Red", "Green", "Blue"], id: \.self) { color in
  Text(color)
}
A list with fixed rows written directly inside the List.
iOS Swift
List { 
  Text("First item")
  Text("Second item")
  Text("Third item")
}
A list with custom data type using Identifiable protocol.
iOS Swift
struct Fruit: Identifiable {
  let id = UUID()
  let name: String
}

let fruits = [Fruit(name: "Mango"), Fruit(name: "Peach")]

List(fruits) { fruit in
  Text(fruit.name)
}
Sample App

This app shows a scrollable list of fruit names with a title on top.

iOS Swift
import SwiftUI

struct ContentView: View {
  let fruits = ["Apple", "Banana", "Cherry", "Date"]

  var body: some View {
    NavigationView {
      List(fruits, id: \.self) { fruit in
        Text(fruit)
      }
      .navigationTitle("Fruit List")
    }
  }
}

@main
struct MyApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}
OutputSuccess
Important Notes

List automatically scrolls if items don't fit on screen.

Use id: \.self only for simple, unique data like strings.

For complex data, use Identifiable protocol to help SwiftUI track items.

Summary

List shows many items vertically and scrolls if needed.

Use List(data, id: \.self) for simple lists.

Use Identifiable for custom data types in lists.