SwiftUI 之 List 常见设置

在 SwiftUI 中,List 是非常常用的一个组件。它可以帮助我们快速实现一个列表视图。

假设,我们现在下面这样的一个List示例:

示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
struct ContentView: View {
var books: [String] = ["三国演义","水浒传", "红楼梦", "西游记"]
var body: some View {
VStack {
List(books, id: \.self) { book in
Text(book)
}
.listStyle(.inset)
}
}
}

针对List,我们可以进行很多的样式设置。

改变 List 中分割线的颜色

默认情况下,List中分割线的颜色默认的灰色。想改变它的默认颜色,可以使用下面的这个修饰器:

1
.listRowSeparatorTint(.green)

但是,这这里需要注意的一点就是,这个修饰器我们需要添加到List里面的子视图中,在本示例中为Text,即

1
2
Text(book)
.listRowSeparatorTint(.green)

隐藏分割线

隐藏List中的分割线可以使用listRowSeparator修饰器,它的参数为hiddenvisible

1
.listRowSeparator(.hidden)

自定义 List 滚动区域的背景

iOS 16 之后,List支持自定义它的背景。例如,如果我们要想给 List添加一个背景色:

首先,需要隐藏List的滚动内容背景,即

1
.scrollContentBackground(.hidden)

然后,可以使用background修饰器设置新的背景:

1
2
3
4
.background(
// 使用渐变色作为背景
LinearGradient(colors: [.red, .green], startPoint: .top, endPoint: .center)
)

此时,效果如下:

如果想要让List的显示内容也使用我们自定义的背景颜色,可以让List中的每一行颜色都变为透明色即可

1
.listRowBackground(Color.clear)

效果如下:

完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct ContentView: View {
var books: [String] = ["三国演义","水浒传", "红楼梦", "西游记"]
var body: some View {
VStack {
List(books, id: \.self) { book in
Text(book)
.listRowSeparator(.visible)
.listRowBackground(Color.clear)
.foregroundStyle(.white)
.bold()
.listRowSeparatorTint(.white.opacity(0.5))
}
.scrollContentBackground(.hidden)
.background(
// 使用渐变色作为背景
LinearGradient(colors: [.red, .green], startPoint: .top, endPoint: .center)
)
}
}
}