SwiftUI Codes
Best SwiftUI Code Warehouse

Lesson 5: Lists and ScrollView

Objective:

Learn how to create lists and scrollable content.

Content:

1. List View

The List view displays a collection of rows, which can be static or dynamic.

Creating a Static List:

List {
    Text("Item 1")
    Text("Item 2")
    Text("Item 3")
}

Explanation:

Dynamic Lists:

Dynamic lists use an array of data to populate their rows.

let items = ["Item 1", "Item 2", "Item 3"]

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

Explanation:

2. Customizing List Items

Using a model to create custom list items.

Example:

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

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

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

Explanation:

3. ScrollView

The ScrollView allows for scrolling content within a view.

Creating a Scrollable View:

ScrollView {
    VStack {
        ForEach(0..<50) { index in
            Text("Item \(index)")
                .padding()
        }
    }
}

Explanation:

4. LazyVStack and LazyHStack

Using LazyVStack and LazyHStack for efficient rendering of large lists.

Efficient Rendering:

ScrollView {
    LazyVStack {
        ForEach(0..<100) { index in
            Text("Lazy Item \(index)")
                .padding()
        }
    }
}

Explanation:

Lesson 6: Data Binding and State Management