我有SwiftUI和XCode 11.2.1环境。
struct Todo: Codable, Identifiable {
let userId, id: Int
let title: String
let completed: Bool
enum CodingKeys: CodingKey {
case userId, id, title, completed
}
}
// SOME STUFF HERE ...
struct ContentView: View {
// SOME STUFF HERE...
var body: some View {
NavigationView {
VStack (spacing: 15){
Text("Number of items: \(todoData.todos.count)"
ForEach(self.todoData.todos) { str in Text(String(str.title));} // works
List(self.todoData.todos) { todo in
Text(todo.title) // works
}
但是,下面的ForEach循环根本不显示文本,在这里我使用todoData.todos.count:
ForEach(0 ..< (todoData.todos.count)) {
Text(String(self.todoData.todos[$0].userId))
}
当我使用以下代码时,出现在Picker人群中:
Picker( selection: $selectedItem, label: Text("MyItems"), content:
{
ForEach(self.todoData.todos) { str in Text(str.title);}
}
)
=- 除了“ MyItems”选择器名称和选择器列表的2行空白外,什么都没有显示。
任何建议/帮助将不胜感激。
=-
data is as follows:
[
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
"userId": 1,
"id": 3,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
"userId": 2,
"id": 4,
"title": "quis ut nam facilis et officia qui",
"completed": false
}
]
答案 0 :(得分:0)
您可以尝试一下,它可以在我的Xcode中使用:
@State var selectedItem: String = ""
var body: some View {
NavigationView {
VStack (spacing: 15){
Text("Number of items: \(todos.count)")
ForEach(self.todos) { str in Text(String(str.title));} // works
List(self.todos) { todo in
Text(todo.title) // works
}
ForEach(0 ..< (todos.count)) {
Text(String(self.todos[$0].userId))
}
Picker(selection: self.$selectedItem, label: Text("MyItems")) {
ForEach(self.todos) { str in Text(str.title).tag(str.title) ;}
}
}}}}