SwiftUI .onDelete 从 ForEach 获取 var
Posted
技术标签:
【中文标题】SwiftUI .onDelete 从 ForEach 获取 var【英文标题】:SwiftUI .onDelete get var from ForEach 【发布时间】:2020-08-12 08:49:19 【问题描述】:我有这个代码:
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
的 UUID
有没有人知道一种方法,我如何从x
获取 UUID?
这是我的第一个 swift 应用程序,我正在努力学习它,但在某些情况下,它与我所知道的其他语言不同。通常我会将一个值解析为一个删除函数,然后遍历它以查找和删除特定的行/数据,但我猜想它是另一种方式。
【问题讨论】:
【参考方案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
【讨论】:
以上是关于SwiftUI .onDelete 从 ForEach 获取 var的主要内容,如果未能解决你的问题,请参考以下文章
SwiftUI .onDelete 抛出致命错误:索引超出范围