The List in Swift UI - Part 1 - A Simple List


List is one of the most important controls in SwiftUI, because hardly any application can do without it. On the iOS platform, it is often unavoidable to display data in lists, because the small screen often does not allow any other meaningful display. From the list, it is often possible to navigate to a detailed view of the selected data. Good examples of this approach are the options of iOS or the eMail app on the iPhone.

Unsurprisingly, a List is defined with the identifier List, followed by a block of curly braces. The brackets contain the contents of the list, i.e. the elements that are to be displayed as a list. If you want it to be very simple, a ForEach loop will suffice, which runs through a range of numbers. As shown in the following listing.

import SwiftUI


struct ContentViewView {

       

   var body: some View {

       

       List{

           ForEach (1...10, id: \.self) { number in

               Text("\(number)").font(.headline)

           }

       }

    }

}

Stacks Image 195

It should be mentioned that in SwiftUI only a ForEach loop can be used. The For loop is not available there. This will also be due to the fact that the elements in the list must be uniquely identifiable. This is done in the shown example with id: \.self. The number itself is used for identification. This works fine as long as all numbers are different.

The content of the list does not necessarily have to be generated with a loop. Static elements that are stored directly in the code are also possible. It even works to mix both types. The following listing shows a list with the names of cities. Two names are stored directly in the code. The other list elements are generated with a ForEach loop that gets its data from an array. No difference can be seen on the graphical interface.

import SwiftUI


struct ContentViewView {

  

    var cities = ["London""Berlin""Tokyo""Amsterdam""Paris""Rom" ]

        

    var body: some View {

   

        List{

            Text("Madrid")

                .font(.headline)

            

            Text("Buenos Aires")

                .font(.headline)

            

            ForEach (cities, id: \.self) { city in

                Text("\(city)").font(.headline)

            }

        }

    }

}

Stacks Image 199

Written: 2021-07-05
Tags: SwiftUI, List