繁体   English   中英

在列表中指定键路径 Swift UI

[英]Specify Key Path in a List Swift UI

我有以下结构,其中GroceryData有关于该部分的详细信息为[GrocerySection] ,这反过来又具有在该部分中显示为[Grocery]的项目。

struct GroceryData {
    var showFavorites:Bool = false
    var sections:[GrocerySection] = [GrocerySection(sectionName: "Common Items")]

}

struct GrocerySection {
    var sectionName:String
    var items:[Grocery] = [Grocery(id:1, name: "Milk", isFavorite: true, price: 1.99)]
}



struct Grocery: Identifiable,Hashable, Codable {
    var id:Int
    var name:String
    var isFavorite:Bool
    var price:Float
}

可识别属性的关键路径应该是什么。

struct ContentView: View {

    var data:GroceryData
    var body: some View {
        List(data.sections, id: \GrocerySection.items.id) { (item) -> Text in
            Text("Hello")
        }
    }
}

在此处输入图像描述

由于您正在处理部分,因此这可能有效:

    List(data.sections, id: \.self.sectionName) { section in
        Text("hello section \(section.sectionName)")
    }

只要 sectionName 是唯一的,否则你总是可以添加和 id 字段。

如果你想遍历项目,你可以试试这个:

    List(data.sections, id: \.self.sectionName) { section in
        ForEach(section.items) { item in
            Text("\(item.name)")
        }
    }

您迭代部分列表,因此GrocerySection必须是可识别的,例如

struct GrocerySection: Identifiable {
    var id = UUID()        // << this
//     var id: String { sectionName }   // << or even this
    var sectionName:String
    var items:[Grocery] = [Grocery(id:1, name: "Milk", isFavorite: true, price: 1.99)]
}

然后你可以写

List(data.sections) { (section) -> Text in
    Text("Hello")
}

或者如果每个部分名称都是唯一的,则使用 keypath,如

List(data.sections, id: \.sectionName) { (section) -> Text in
    Text("Hello")
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM