Learn How to Create Lists in SwiftUI

Tim Moose Tutorials

Creating a scrolling list using UIKit comes with a bunch of boilerplate, cell dequeuing, etc. but SwiftUI has made that process so much easier!

Let’s break down what’s going on in the code here:

First, on line 4 you have an array of Character objects. That array is the data source that is used to populate the list. Each Character object in this example has a unique id (required for lists), a name, description, and an image associated with it.

Line 7 is where the list itself is created. The characters array is passed in as the content for the list, which tells the list where it is going to get its data from. Following that there is a closure for setting up each cell within the list, using each item out of the source data (which in this case is the characters array).

In this example, I have a few things added to each cell on the next few lines – an image and a vertical stack view holding the name and description. If you wanted to keep it really simple you could just as easily add a single label with the character’s name with Text(character.name) and you would get a list of cells displaying the character names.

The last bit at the bottom is just some test data for display in the preview window on the right.

You can check out the whole file below

And here is what the Character struct looks like