Dynamic lists in SwiftUI

Bhoopendra Umrao
2 min readApr 28, 2023

--

SwiftUI is a modern framework for building user interfaces across Apple’s platforms. With SwiftUI, you can create dynamic lists that can show a large number of items in a scrollable view. Here’s how to implement dynamic lists in SwiftUI:

1. Define your data model:

First, you need to define your data model that conforms to the Identifiable protocol. The Identifiable protocol requires that each item in your list has a unique identifier.

struct Item: Identifiable {
let id = UUID()
let name: String
}

2. Declare your list view:

Next, declare your list view in the body of your SwiftUI view. Use the ForEach loop to iterate over your data model and display each item in the list.

struct MyListView: View {

// Data model
let items = [Item(name: "Item 1"), Item(name: "Item 2"), Item(name: "Item 3")]

var body: some View {
List {
ForEach(items) { item in
Text(item.name)
}
}
}
}

3. Add dynamic behavior to your list:

To add dynamic behavior to your list, use the onAppear and onDelete modifiers. The onAppear modifier is called when a new row is about to appear, and the onDelete modifier is called when a row is deleted from the list.

struct MyListView: View {

// Data model
@State var items = [Item(name: "Item 1"), Item(name: "Item 2"), Item(name: "Item 3")]

var body: some View {
List {
ForEach(items) { item in
Text(item.name)
}
.onDelete { indexSet in
self.items.remove(atOffsets: indexSet)
}
.onAppear {
self.loadItems()
}
}
}

// Fetch items from a data source
func loadItems() {
// Load data here and update the items state variable
}
}

In conclusion, implementing dynamic lists in SwiftUI is a simple yet powerful feature that can help you create complex user interfaces in a few lines of code. With the ability to add dynamic behavior, such as onAppear and onDelete, you have the flexibility to create user interfaces that can handle a large amount of data.

--

--