【发布时间】:2021-08-18 10:51:45
【问题描述】:
问这个我觉得有点尴尬,但经过一天多的尝试,我被困住了。根据对其他问题的回复,我对代码进行了一些更改。最新的代码本质上是根据 UUID 选择列表中的项目。
这导致我的删除功能停止工作,因为我正在将Int 作为要删除的选定元素传递。我最初是在实现like this。
代码如下,我仍在试图找出解决 SwiftUI 的方法,但问题是,我现在如何根据 UUID 而不是通常选择的方式删除列表(及其后面的数组)上的项目项目。
如果它有所作为,这适用于 macOS Big Sur。
代码:
struct NoteItem: Codable, Hashable, Identifiable {
let id: Int
var text: String
var date = Date()
var dateText: String {
dateFormatter.dateFormat = "EEEE, MMM d yyyy, h:mm a"
return dateFormatter.string(from: date)
}
var tags: [String] = []
}
struct AllNotes: View {
@EnvironmentObject private var data: DataModel
@State var noteText: String = ""
@State var selectedNoteId: UUID?
var body: some View {
NavigationView {
List(data.notes) { note in
NavigationLink(
destination: NoteView(note: note),
tag: note.id,
selection: $selectedNoteId
) {
VStack(alignment: .leading) {
Text(note.text.components(separatedBy: NSCharacterSet.newlines).first!)
Text(note.dateText).font(.body).fontWeight(.light)
}
.padding(.vertical, 8)
}
}
.listStyle(InsetListStyle())
}
.navigationTitle("A title")
.toolbar {
ToolbarItem(placement: .navigation) {
Button(action: {
data.notes.append(NoteItem(id: UUID(), text: "New Note", date: Date(), tags: []))
}) {
Image(systemName: "square.and.pencil")
}
}
ToolbarItem(placement: .automatic) {
Button(action: {
// Delete here????
}) {
Image(systemName: "trash")
}
}
}
.onAppear {
DispatchQueue.main.async {
selectedNoteId = data.notes.first?.id
}
}
.onChange(of: data.notes) { notes in
if selectedNoteId == nil || !notes.contains(where: { $0.id == selectedNoteId }) {
selectedNoteId = data.notes.first?.id
}
}
}
}
我原来的removeNote是这样的:
func removeNote() {
if let selection = self.selectedItem,
let selectionIndex = data.notes.firstIndex(of: selection) {
print("delete item: \(selectionIndex)")
data.notes.remove(at: selectionIndex)
}
}
【问题讨论】:
标签: macos swiftui macos-big-sur