【问题标题】:SwiftUI, List from the JSON file shows only the first elementSwiftUI,JSON文件中的列表仅显示第一个元素
【发布时间】:2020-07-01 12:34:20
【问题描述】:

请用 JSON 帮助理解 SwiftUI json文件读取并打印,但是当你创建一个List时,它只读取第一个元素..我做错了什么???

struct ContentView: View {
    var fetch = Fetch()
    
    public var body: some View {
      
//        Text(fetch.persons.description)
        List(fetch.persons){ user in
            Text(user.name)
            }
    }
}

【问题讨论】:

  • 确保id 属性已设置并且是唯一的;否则,您可以执行 List(fetch.persons, id: \.self) 之类的操作
  • @New Dev ,我在模型和视图中写了 public var id = UUID() - List(fetch.persons, id:\.self){ user in Text(user.name) }。 Xcode write me -Initializer 'init(_:id:rowContent:)' 要求 'LibraryElement' 符合 'Hashable'
  • 你的意思是,你以前有过吗?还是你现在做的?
  • @New Dev,我现在做到了
  • 好吧..它没有解决问题? (我还看到您更改了上面的评论。如果您有id 属性,则无需执行List(..., id: \.self) - 只需将其保留为List(fetch.persons) { ... }

标签: json swiftui swiftui-list


【解决方案1】:

List 与符合Identifiable 的对象一起使用,id 用于唯一标识每个对象,这就是List 能够跟踪插入、删除和编辑的方式。

在您的情况下,idnil,这会破坏它。

相反,请确保 id 唯一标识列表中的每个对象:

struct Foo: Identifiable {
  var id = UUID()
  // ...
}
var foos: [Foo]
List(foos) { foo in 
   // ...
}

或者,您需要为可以充当唯一 id 的属性提供 KeyPath(并且它需要符合 Hashable),这可能是元素本身。

struct Foo: Hashable { }
var foos: [Foo]
List(foos, id: \.self) {
  // ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    相关资源
    最近更新 更多