SwiftUI:从 ObservableObject 读取数据
SwiftUI: reading data from ObservableObject
我是 SwiftUI 的新手并创建了一个 Todo
模型。然后我有一个代表容器的 class ,这样我以后就可以在它上面有一组待办事项和方法。我做了 TodoContainer
一个 ObservableObject
然后实例化后观察它:@ObservedObject var items = TodoContainer()
.
我正在遍历列表并期待每次单击按钮时,它不应该出现在列表中,因为它每次都创建一个新的待办事项并且 allTodos
应该有所有待办事项的数组?
import SwiftUI
struct Todo: Identifiable {
var id = UUID()
var name: String;
var priority: Int;
}
class TodoContainer: ObservableObject {
@Published var allTodos = [Todo]();
}
struct ContentView: View {
@ObservedObject var items = TodoContainer()
var body: some View {
Button("Create New") {
Todo(name: "New one", priority: Int.random(in: 1..<100))
}
List(items.allTodos, id: \.id){item in
Text(item.name)
}
}
}
您需要将创建的待办事项添加到视图模型的 allTodos
。 Xcode 之前可能已向您显示有关未使用的表达式的错误。
import SwiftUI
struct Todo: Identifiable {
var id = UUID()
var name: String;
var priority: Int;
}
class TodoContainer: ObservableObject {
@Published var allTodos = [Todo]();
}
struct ContentView: View {
@ObservedObject var items = TodoContainer()
var body: some View {
Button("Create New") {
let todo = Todo(name: "New one", priority: Int.random(in: 1..<100))
items.allTodos.append(todo) // here
}
List(items.allTodos, id: \.id){item in
Text(item.name)
}
}
}
我是 SwiftUI 的新手并创建了一个 Todo
模型。然后我有一个代表容器的 class ,这样我以后就可以在它上面有一组待办事项和方法。我做了 TodoContainer
一个 ObservableObject
然后实例化后观察它:@ObservedObject var items = TodoContainer()
.
我正在遍历列表并期待每次单击按钮时,它不应该出现在列表中,因为它每次都创建一个新的待办事项并且 allTodos
应该有所有待办事项的数组?
import SwiftUI
struct Todo: Identifiable {
var id = UUID()
var name: String;
var priority: Int;
}
class TodoContainer: ObservableObject {
@Published var allTodos = [Todo]();
}
struct ContentView: View {
@ObservedObject var items = TodoContainer()
var body: some View {
Button("Create New") {
Todo(name: "New one", priority: Int.random(in: 1..<100))
}
List(items.allTodos, id: \.id){item in
Text(item.name)
}
}
}
您需要将创建的待办事项添加到视图模型的 allTodos
。 Xcode 之前可能已向您显示有关未使用的表达式的错误。
import SwiftUI
struct Todo: Identifiable {
var id = UUID()
var name: String;
var priority: Int;
}
class TodoContainer: ObservableObject {
@Published var allTodos = [Todo]();
}
struct ContentView: View {
@ObservedObject var items = TodoContainer()
var body: some View {
Button("Create New") {
let todo = Todo(name: "New one", priority: Int.random(in: 1..<100))
items.allTodos.append(todo) // here
}
List(items.allTodos, id: \.id){item in
Text(item.name)
}
}
}