【问题标题】:Specify Key Path in a List Swift UI在列表 Swift UI 中指定键路径
【发布时间】:2020-08-10 12:05:57
【问题描述】:

我有以下结构,其中 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")
        }
    }
}

【问题讨论】:

    标签: xcode list swiftui swift-keypath


    【解决方案1】:

    由于您正在处理部分,这可能会起作用:

        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)")
            }
        }
    

    【讨论】:

    • 可能不会,因为随着进一步的变化,它会在内容中包含 Row 项目
    • 不完全理解您的评论。代码是否有效?你想循环一些其他的东西吗?
    • items.id 需要一个可识别的 KeyPath,其中 items 是 Grocery 类型的数组。 Grocery 对象的 id 类型为 Int,并且 Grocery 符合 Identifiable 协议
    • 您的 List 用于 GrocerySection 数组,它需要 GrocerySection 的 id 和 sectionName 或 items。但是 items 只是一个数组,它并不能真正识别不同的部分。从您的代码看来,您似乎希望从列表中获得一个 Grocery 项目,但您只能获得一个 GrocerySection。一旦你有了它,你就可以得到这些项目。
    【解决方案2】:

    您迭代部分列表,因此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")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-19
      • 2019-05-03
      相关资源
      最近更新 更多