DEV Community

Cover image for Display a list using SwiftUI
Rafael Adolfo
Rafael Adolfo

Posted on

Display a list using SwiftUI

SwiftUI provides an easy and fast way to build user interfaces for apple devices.

This series will show you how to:

  • Display an array in a list
  • Adapt the list to display using MVVM and Observables
  • Create a navigation link, to show the item details
  • Get the list from an API

Create the project

Open Xcode and create a new project using SwiftUI as User Interface:
Alt Text

Replace the initial code in the file ContentView.swift with the code bellow:

import SwiftUI

struct ContentView: View {
    private var itemList = [  "iPhone",
                              "iPad",
                              "MacBook Pro",
                              "Macbook Air"  ]

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

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Enter fullscreen mode Exit fullscreen mode

Explaining the code

What list does?
From apple:

List
A container that presents rows of data arranged in a single column.

So here, we are using List as a container for our declared array of strings variable:

private var itemList = [  "iPhone",
                              "iPad",
                              "MacBook Pro",
                              "Macbook Air"  ]
Enter fullscreen mode Exit fullscreen mode

And inside the list, we are looping all contents of the itemList array:

ForEach(self.itemList, id: \.self) { item in
    Text(item)
}
Enter fullscreen mode Exit fullscreen mode

This means that for each item inside our array, we create a new Text() to display the value of that item.

What the ForEach loop is doing, is the same as this code:

List {
  Text("item 1")
  Text("item 2")
}
Enter fullscreen mode Exit fullscreen mode

Hit the play button and this should be the final result:

Alt Text

Alright! You have now created a list of items using SwiftUI.
Next, let's use MVVM as architecture pattern with the help of Observables.

The complete code is available @ Github

Top comments (0)