SwiftUI List
Joash Tubaga
04 May 2021
The List type provided by SwiftUI is similar to UITableView, and allows easy creation of list of child elements. These child elements can be static or dynamically generated from collections of data like arrays. The List can also be stylized to match its content.
Basic Code Example
List { Text("Hello") Text("World!") Text("!") } List { HStack { Text("Hello") Text("World!") } }
The example in line 1 is a basic List of text elements. This will create a scrollable vertical list with 3 lines of text. As seen in line 7, Lists can take in other views such as Stacks, Images, and custom defined views.
Note that Lists function similar to ScrollView, but Lists cannot be formatted horizontally.
Dynamic Lists
struct Animal: Identifiable { let name: String let id = UUID() } let animals = [ Animal(name: "Dog"), Animal(name: "Cat"), Animal(name: "Bird") ] var body: some View { List (animals) { animal in Text(animal.name) } }
Lists are often used to create views based on a collection of data. In the example above, an array of animals is passed into the List, and the List displays the name for each ‘animal’ element of the array. Note that the elements of the passed in array must conform to the Identifiable protocol, with each element having an ID as shown in line 3.
Stylizing the List
struct Animal: Identifiable { let name: String let id = UUID() } let animals = [ Animal(name: "Dog"), Animal(name: "Cat"), Animal(name: "Bird") ] var body: some View { List (animals) { animal in Text(animal.name) } .listStyle(SidebarListStyle()) }
To change the basic style of the List, add the .listStyle modifier as seen in line 16. The listStyle modifier takes in a ListStyle type, which includes SidebarListStyle, GroupedListStyle, InsetListStyle, and a few more.
Bonus: Sectioned Lists
struct Breed: Identifiable { let name: String let id = UUID() } struct Animal: Identifiable { let name: String let breeds: [Breed] let id = UUID() } let animals = [ Animal(name: "Dog", breeds: [Breed(name: "Bulldog"), Breed(name: "German Shepard"), Breed(name: "Golden Retriever")]), Animal(name: "Cat", breeds: [Breed(name: "Siamese"), Breed(name: "Persian"), Breed(name: "Bengal")]), Animal(name: "Bird", breeds: [Breed(name: "Parrot"), Breed(name: "Dove"), Breed(name: "Finch")]) ] var body: some View { List { ForEach(animals) { animal in Section(header: Text(animal.name)) { ForEach(animal.breeds) { breed in Text(breed.name) } } } } }
Sectioned lists can be created for data that is categorized into different sections. In the example above, we added an array of breeds for each animal type. In the List itself in line 19, we use ForEach() to go through each animal type and create section headers, and then we go through each breed name.