ios 如何在SWIFTUI的视图中循环HashMap样式

wi3ka0sx  于 2023-02-10  发布在  iOS
关注(0)|答案(1)|浏览(149)
var someProtocol = [SurveyItems : [Surveys]]()

sectionLabels.forEach{ a in
    var finalSurveys = [Surveys]()
    surveys.forEach{ b in
        if a.groupHeader == b.group_survey {
            finalSurveys.append(b)
        }
        someProtocol[a] = finalSurveys
    }
}

我想使用someProtocol动态显示标签部分和该部分下的调查。

for (Surveys, SurveyItems) in someProtocol {
    Text(Surveys.sectionTitle)
    for survey in SurveyItems {
        Text(survey.label)
    }
}

我尝试ViewBuider,但得到一些错误.

fnx2tebb

fnx2tebb1#

要在视图中循环显示someProtocol字典,请尝试以下示例代码:根据您自己的目的调整代码。注意,在SwiftUI视图中,您需要使用ForEach而不是“正常”swift for x in ...来循环序列。

struct ContentView: View {
    @State var someProtocol = [SurveyItems : [Surveys]]()
    
    var body: some View {
        List(Array(someProtocol.keys), id: \.self) { key in
            VStack {
                if let surveys = someProtocol[key] {
                    Text(key.title).foregroundColor(.red)
                    ForEach(surveys, id: \.self) { survey in
                        Text("survey \(survey.label)")
                    }
                }
            }
        }
        .onAppear {
            // for testing
            someProtocol[SurveyItems(id: "1", number: 1, title: "title-1")] = [Surveys(id: "s1", label: "label-1"), Surveys(id: "s2", label: "label-2")]
            someProtocol[SurveyItems(id: "2", number: 2, title: "title-2")] = [Surveys(id: "s3", label: "label-3")]
        }
    }

}

struct SurveyItems: Identifiable, Hashable {
    let id: String
    let number: Int
    var title: String
}

struct Surveys: Identifiable, Hashable {
    let id: String
    let label: String
}

相关问题