SwiftUI 的@ViewBuilder 有一個限制,單個@ViewBuilder block 如果繪制超過10個View,系統(tǒng)就會報錯,比如 Ambiguous reference to member 'buildBlock()'錯誤
如圖 所示

9FDDC5CD-B03B-462F-9C74-429370AFC806.png
解決辦法如下
1. 可以直接在block 內(nèi)部用 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. 如果是一類相同類型的數(shù)據(jù)或者符合一定的規(guī)則,使用動態(tài)繪制,如下所示
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)
}
}
}
}