Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Customize List Rows in SwiftUI
Written by Team Kodeco

Lists are versatile components in iOS applications, effortlessly displaying scrollable, data-rich interfaces. SwiftUI enhances this feature with the List view, showcasing an array of data as a series of rows. Beyond its simplicity, SwiftUI’s List offers a significant advantage – customization.

To personalize the appearance of List rows, you employ the listRowBackground modifier. This modifier accepts a view, which then becomes the background of the row, allowing for diverse visual designs.

Consider a simple List of names:

struct ContentView: View {
  let names = ["Alice", "Bob", "Charlie", "Dave"]

  var body: some View {
    List(names, id: \.self) { name in
      Text(name)
    }
  }
}

By default, these rows sport a plain white background. However, let’s say you desire a green background instead. Achieve this with the listRowBackground modifier:

struct ContentView: View {
  let names = ["Alice", "Bob", "Charlie", "Dave"]

  var body: some View {
    List(names, id: \.self) { name in
      Text(name)
        .listRowBackground(Color.green)
    }
  }
}

Here’s what your preview should look like:

A List where the rows have a green background in SwiftUI.
A List where the rows have a green background in SwiftUI.

Each row now has a green background, distinguishing them distinctly.

The listRowBackground modifier isn’t limited to color changes. You can introduce rounded corners, shadows or any custom background. Simply provide your preferred background view as the parameter to listRowBackground, and you obtain full control over your List rows.

For instance, you can create a gradient background:

struct ContentView: View {
  let names = ["Alice", "Bob", "Charlie", "Dave"]

  var body: some View {
    List(names, id: \.self) { name in
      Text(name)
        .listRowBackground(
          LinearGradient(gradient: Gradient(colors: [.blue, .purple]),
                         startPoint: .leading,
                         endPoint: .trailing)
        )
    }
  }
}

A list where the rows have a gradient background in SwiftUI.
A list where the rows have a gradient background in SwiftUI.

In summary, SwiftUI’s listRowBackground modifier unlocks powerful ways to personalize List row appearances. It lets you craft polished and cohesive user interfaces, aligning perfectly with your app’s aesthetic requirements. Experiment with this versatility to create compelling SwiftUI List views.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.