SwiftUI 中列表的推荐方式是使用 List 作为控件(类似 UITableView)。通常我们使用列表的时候都有修改背景色或者自定义背景的需求。
起初,你以为像其他控件一样使用 background 就可以了,比如这样:
swift
List {
Section {
Text("Item 1")
}
Section {
Text("Item 2")
Text("Item 3")
Text("Item 4")
}
Section {
Text("Item 5")
Text("Item 6")
Text("Item 7")
}
}
.background(.pink)
然而你跑起来以后会发现这个背景没起作用。
经过视图调试你会发现,是因为 tableView 控件自带了一个背景,我们自定义的背景在 List 的下面一层,被遮住了,所以没有效果。

难道就没有一个隐藏 List 背景图层的接口吗?
一问一个不吱声,iOS 16之前还真没有。

在 iOS 16 上终于良心发现增加了一个 scrollContentBackground(.hidden)
。
swift
List {
Section {
Text("Item 1")
}
Section {
Text("Item 2")
Text("Item 3")
Text("Item 4")
}
Section {
Text("Item 5")
Text("Item 6")
Text("Item 7")
}
}
.background(.pink)
.scrollContentBackground(.hidden)
隐藏了原生列表的背景图层以后自定义的背景就可以正常使用了。

使用图片之类的是也可以的。
