SwiftUI 隨手筆記-解決@ViewBuilder block中 Ambiguous reference to member 'buildBlock()'錯誤

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)
            }
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容