簡體   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