SwiftUI: List & Navigation Part 1

Pankaj Talreja
3 min readJun 15, 2020

--

In this blog, I am going to cover List(TableView) in part 1 and Navigation to the “Detail” page in part 2.

Figure 1. Home page with a list of fruits

In the last post, I have listed most of the elements of SwiftUI which is equivalent to UIKit. In SwiftUI, to create the Table view you need to use “List” instead of UITableView

While implementing UITableView, you are obligated to conform to the UITableViewDataSource and also need to confirm the protocol UITableViewDelegate to perform a certain action, change in layouts of the cell, and many more.

Below is the screenshot of code snippet for basic List view using SwiftUI:

In the above example, there are two parameters assigned to the list.

Parameters details:1) An array of fruits detail which we are going to display on List

2) id: Generates a uniquely identified view that can be inserted or removed. To handle dynamic items, you must identify the cells. This is done using the Identifiable protocol by defining id value. Here I defined value to id from model I have created for fruits.

//Line 2: HStack arranges the elements Horizontally. Additionally, you can define the alignments also.

//Line 3: It will display image 1st before the other elements. Also, you can define the other attributes to change the layouts of images. In our above example, I have resized the image with attributes like .resizable, change the frame size, set the corner of the image, and also apply aspect ratio.

//Line 9: The elements inside the VStack will be arranged in vertically and leading alignment. However in the example, “Name of fruit” and “Click to see the benefits” will be vertically aligned.

Although, elements inside VStack(consolidated view) will be horizontally aligned with Image as you can see in below Image(Text “Apple and Click to see the benefits” are arranged vertically however Image is arranged Horizontally to the whole VStack).

//line 10 and //line 12: Is just to display text in List view. However, you can also define attributes such as padding, font, size of the text, etc.

Below is the screenshot of the cell:

Figure 2. Cell view

This will create the table view with less code and it will be reusable for different screen sizes as well. you don’t require explicitly define the auto layout, SwiftUI will take care of it internally.

And with just 12 lines of code, you have designed the standard table view.

In the next post, I will cover the navigation to the detail page on click of the cell and also I will post the whole code for the reference.

Thank you!!

Stay safe!!!!!

--

--