我有此代码:
struct CreateInfo: Identifiable {
var id: String
var name: String
var time: String
var day: String
var isDeleted: Bool
}
struct ZettelView: View {
@State var zettelInfos = [CreateInfo]()
@State private var showingAlert = false
@State private var savedValueForDeleteFunction: CreateInfo
func createNewInfo() {
var arr = [[String]]()
arr = getZettelData()
for x in arr {
zettelInfos.append(CreateInfo(id: "\(x[0])", name: "\(x[1])", time: "\(x[2])", day: "\(x[3])", isDeleted: false))
}
self.executeThisAsyncThing = false
}
@State var executeThisAsyncThing: Bool = true
var body: some View {
DispatchQueue.main.async {
if self.executeThisAsyncThing {
self.createNewInfo()
}
}
return VStack {
//New - testing
NavigationView {
List {
ForEach(zettelInfos) { x in
NavigationLink(destination: zettelDetailView(uuid: x.id, info: x)) {
Text("\(x.id)")
}
}.onDelete(perform: delete)
}.navigationBarTitle("Einkaufszettel")
.navigationBarItems(trailing: Button(action: {
self.addRow()
}) {
Image(systemName: "plus.app.fill")
})
}
.alert(isPresented: $showingAlert) {
Alert(title: Text(" meImportantssage"), message: Text("Wear sunscreen"), dismissButton: .default(Text("Got it!")))
}
}
}
func delete(at offsets: IndexSet) {
zettelInfos.remove(atOffsets: offsets)
self.showingAlert = true
}
private func addRow() {
let dateAndTime = Date()
let dfDay = DateFormatter()
let dfTime = DateFormatter()
dfDay.dateFormat = "dd.MM.yyyy"
dfTime.dateFormat = "HH:mm:ss"
let day = dfDay.string(from: dateAndTime)
let time = dfTime.string(from: dateAndTime)
let x = CreateInfo(id: UUID().uuidString, name: "Neuer Zettel", time: time, day: day, isDeleted: false)
saveZettelData(x: x)
zettelInfos.append(x)
}
}
所以我的问题是,如何将ForEach中的x变量解析为删除函数?
我为什么要这个? -> foreach中的x变量有一个UUID,我需要x
你们中有人知道一种如何从x
获取UUID的方法吗?
这是我的第一个快速应用程序,我正在尝试学习它,但是在某些情况下,它的方式与我所知道的其他语言不同。通常,我会将一个值解析为一个删除函数,然后遍历它以查找和删除特定的行/数据,但是我想这是另一种快速的方法。
答案 0 :(得分:1)
这里是拥有它的一种方式
func delete(at offsets: IndexSet) {
let index = offsets[offsets.startIndex]
let x = zettelInfos[index]
// ... do anything needed with x.id now
zettelInfos.remove(atOffsets: offsets)
self.showingAlert = true
}