SwiftUI Background Color List Tutorial
The background color of items inside a List view can be changes using the .listRowBackground modifier. In this tutorial a list is displayed with alternate colors. This tutorial is built for iOS14 and Xcode 12, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUIListBackgroundColorTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbos and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to
struct ContentView: View { // 1. @State private var items = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"] var body: some View { List { // 2. ForEach(items.indices) { index in // 3. Text(items[index]) .listRowBackground((index % 2 == 0) ? Color(.systemBlue) : Color(.yellow)) } } } }
a State properties is declared which holds the array of numbers as strings.
A List is displayed containing the items of the array.
The .listRowBackground modifier set the background color for each item. the module operator is used to alternate the colors.
Go to the Preview to view the items with alternate background colors in the List.
The source code of the SwiftUIListBackgroundColorTutorial can be downloaded at the ioscreator repository on Github.














