0
0
iOS Swiftmobile~20 mins

List view basics in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple List Screen
This screen shows a list of fruits. Each fruit name is shown in a row. The list is scrollable if needed.
Target UI
---------------------
| Simple List Screen |
---------------------
| Apple             |
| Banana            |
| Cherry            |
| Date              |
| Elderberry        |
| Fig               |
| Grape             |
---------------------
Use SwiftUI List to display a list of fruit names
Show at least 7 fruit names as rows
Each row should show the fruit name as text
The list should be scrollable if the content is longer than the screen
Starter Code
iOS Swift
import SwiftUI

struct SimpleListScreen: View {
    let fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape"]

    var body: some View {
        // TODO: Add your List view here
        Text("Replace this with a List")
    }
}

struct SimpleListScreen_Previews: PreviewProvider {
    static var previews: some View {
        SimpleListScreen()
    }
}
Task 1
Task 2
Task 3
Solution
iOS Swift
import SwiftUI

struct SimpleListScreen: View {
    let fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape"]

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

struct SimpleListScreen_Previews: PreviewProvider {
    static var previews: some View {
        SimpleListScreen()
    }
}

We use a List view to show a scrollable list of items. The fruits array holds the fruit names. We pass this array to the List and provide an identifier using id: \.self because the items are strings and unique. Each row shows the fruit name inside a Text view. Wrapping the list in a NavigationView allows us to add a title at the top with navigationTitle. This creates a simple, scrollable list screen.

Final Result
Completed Screen
---------------------
| Simple List Screen |
---------------------
| Apple             |
| Banana            |
| Cherry            |
| Date              |
| Elderberry        |
| Fig               |
| Grape             |
---------------------
User can scroll up and down if the list is longer than the screen
Each row shows the fruit name clearly
Stretch Goal
Add a navigation bar button labeled 'Add' that prints 'Add tapped' to the console when tapped.
💡 Hint
Use the .toolbar modifier on the NavigationView and add a Button with an action that calls print("Add tapped")