How to Fix SwiftUI List Not Displaying Correctly
In this tutorial, you'll learn about How to Fix SwiftUI List Not Displaying Correctly. We cover key concepts, practical examples, and best practices.
The Problem
SwiftUI List is not working as expected:
List content is empty or not updating.
Quick Fix
Step 1: Use the correct data source
WRONG — passing a non-Identifiable type:
struct Item {
let name: String
}
List(items, id: \.name) { item in // OK but requires explicit id
Text(item.name)
}
RIGHT — use Identifiable:
struct Item: Identifiable {
let id = UUID()
let name: String
}
List(items) { item in
Text(item.name)
}
Step 2: Use ForEach inside List
List {
Section("Fruits") {
ForEach(fruits) { fruit in
Text(fruit.name)
}
}
Section("Vegetables") {
ForEach(vegetables) { vegetable in
Text(vegetable.name)
}
}
}
Step 3: Enable dynamic updates
@State private var items = [Item(name: "Apple"), Item(name: "Banana")]
var body: some View {
List {
ForEach(items) { item in
Text(item.name)
}
.onDelete { indexSet in
items.remove(atOffsets: indexSet)
}
}
}
Step 4: Add pull-to-refresh
List(items) { item in
Text(item.name)
}
.refreshable {
await refreshItems()
}
Step 5: Style the list
List(items) { item in
Text(item.name)
}
.listStyle(.insetGrouped) // .plain, .grouped, .inset, .insetGrouped
Step 6: Use LazyVStack for custom layouts
ScrollView {
LazyVStack {
ForEach(items) { item in
Text(item.name)
.padding()
}
}
}
Prevention
- Always make list items conform to
Identifiable. - Use
ForEachinsideListfor dynamic content with actions. - Use
.refreshablefor pull-to-refresh instead of UIKit integration.
Common Mistakes with swiftui list
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world IOS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro