SwiftUI 的@ViewBuilder 有一个限制,单个@ViewBuilder block 如果绘制超过10个View,系统就会报错,比如 Ambiguous reference to member 'buildBlock()'错误
如图 所示
9FDDC5CD-B03B-462F-9C74-429370AFC806.png
解决办法如下
1. 可以直接在block 内部用 Group,Section,Stack之类容器来拆分,如下所示
struct ContentView: View {
var body: some View{
List {
Section {
Text("hello workld 1")
Text("hello workld 2")
Text("hello workld 3")
}
Section {
Text("hello workld 4")
Text("hello workld 5")
Text("hello workld 6")
}
Section {
Text("hello workld 7")
Text("hello workld 8")
Text("hello workld 9")
Text("hello workld 10")
Text("hello workld 11")
}
}
}
}
2. 可以在外部定义好分割的View,如下所示
struct ContentView: View {
var body: some View {
List {
headerSection
contentSection
footerSection
}
}
private var headerSection: some View {
Section {
Text("hello workld 1")
Text("hello workld 2")
Text("hello workld 3")
}
}
private var contentSection: some View {
Section {
Text("hello workld 4")
Text("hello workld 5")
Text("hello workld 6")
}
}
private var footerSection: some View {
Section {
Text("hello workld 7")
Text("hello workld 8")
Text("hello workld 9")
Text("hello workld 10")
Text("hello workld 11")
}
}
}
3. 如果是一类相同类型的数据或者符合一定的规则,使用动态绘制,如下所示
struct ContentView: View {
struct Item: Identifiable {
letid: String
lettext: String
}
private let titles: [Item] = (0...11).compactMap {
Item(id: String($0), text: "hello workld \($0)")
}
var body: some View {
List {
ForEach(titles) {
Text($0.text)
}
}
}
}
网友评论