我有一个现有列表,但我希望能够向其中添加新项目。现在,我正在使用@EnvironmentObject
,但是当我向数组中添加一个元素时,视图没有更新?我在互联网上看到了你使用的解决方案 objectWillChange.send()
,但作为 Swift 的初学者,我不知道如何操纵它来做我想做的事。
班级
class ChecklistObject: ObservableObject {
@Published var description: String
@Published var complete: Bool
let ID: Int
init(_ desc: String, _ complete: Bool, ID: Int){
description = desc
self.complete = complete
self.ID = ID
}
}
class Event: ObservableObject {
@Published var Name: String
@Published var CalendarID: Int
var timeStart: Date
var timeEnd: Date
@Published var checklist = [ChecklistObject]()
@Published var checklistSize = 0
init(_ eventName: String, _ calID: Int, _ timeStart: Date, _ timeEnd: Date) {
Name = eventName
CalendarID = calID
self.timeStart = timeStart
self.timeEnd = timeEnd
logger.log("Successfully created new event")
}
func newChecklistItem(Content: String){
objectWillChange.send()
checklist.append(ChecklistObject(Content, false, ID: getChecklistSize()))
//checklistSize = checklistSize + 1
}
func getChecklistSize() -> Int {
return checklist.count
}
}
列表
VStack (alignment: .leading) {
Text("Checklist")
.font(.title)
.bold()
ForEach(event.checklist.indices) { idx in
ChecklistDisplayRow()
.environmentObject(event.checklist[idx])
}
Spacer()
.frame(width: 360, height: 10)
Button(action: {
event.newChecklistItem(Content: "New item")
event.checklistSize = event.checklistSize + 1
}) {
HStack{
if #available(OSX 11.0, *) {
Image(systemName: "plus.circle")
} else {
Path{ path in
path.move(to: CGPoint(x: 10, y: 20))
path.addLine(to: CGPoint(x: 10, y:0))
path.move(to:CGPoint(x: 0, y: 10))
path.addLine(to: CGPoint(x: 20, y: 10))
}
}
Text("Add new item")
.font(.caption)
}
}
.buttonStyle(PlainButtonStyle())
}
提前致谢。