我希望应用程序中的所有列表看起来完全相同,并且不想一遍又一遍地重新指定所有这些设置。我收到以下错误:在范围内找不到类型“配置”。我目前有这样的东西:
struct CustomListStyle: ListStyle {
func makeBody(configuration: Configuration) -> some View {
ScrollView {
VStack(spacing: 10) {
ForEach(configuration.data, id: \.self) { item in
Text(item as? String ?? "")
.foregroundColor(.blue)
.padding(10)
.background(Color.gray)
.cornerRadius(10)
}
}
.padding()
}
}
}
struct ContentView: View {
var body: some View {
List(0..<10, id: \.self) { index in
Text("Item \(index)")
}
.listStyle(CustomListStyle())
}
}
编辑 - 1 - 这是一个供参考
List( selection: $dm.someVar ) {
Section( ) {
LazyVGrid(columns: [
GridItem(.flexible(minimum: 120)),
], alignment: .leading, spacing: 10) {
ForEach(0..<20, id: \.self) { index in
Text("Column1 abcdef: \(index)")
}
}
}
}
如果您尝试实现
ListStyle
,您可以让 Xcode 添加存根以实现协议一致性。然后你会看到,所需的功能都以_
开头。这是一条线索,您实际上不应该实现自己的ListStyle
。
但是,您可以通过为接受
List
作为参数的 ViewBuilder
创建包装器来实现您想要的目标。比如:
struct CustomList<Content>: View where Content: View {
@ViewBuilder let content: () -> Content
var body: some View {
List {
content()
.foregroundStyle(.pink)
.listRowBackground(
Color.yellow
.clipShape(RoundedRectangle(cornerRadius: 10))
)
}
.listStyle(.plain)
.listRowSpacing(10)
.padding()
.background(.gray)
}
}
struct ContentView: View {
var body: some View {
CustomList {
ForEach(0..<100, id: \.self) { item in
Text("Item \(item)")
}
}
}
}