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:
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)
)
}
}
}
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.