我遇到了问题。我需要使用 .onDelete 函数删除的项目的值。我是新手,我不知道该怎么做。如果有人可以在这里帮助我,那将是很好的。谢谢。
列表:
struct TimeStampList: View {
@EnvironmentObject var user: User
@ObservedObject var viewModel: SingleEntriesViewModel
var body: some View {
List {
ForEach(0..<self.viewModel.timeStamps.count, id: \.self) { timeStamp in
Section(header: Text("\(TimeStamp.convertToReadableString(date: self.viewModel.timeStamps[timeStamp].date))")) {
if (self.viewModel.timeStamps[timeStamp].dayType != "V") {
ForEach(self.viewModel.timeStamps[timeStamp].times, id: \.self) { time in
SingleEntriesRow(time: time, id: UUID())
}.onDelete { times in
self.deleteTimeStamps(timeStamp: timeStamp, row: times)
}
}
else {
Text("V")
}
}
}
}
}
func deleteTimeStamps(timeStamp: Int, row: IndexSet) {
self.viewModel.timeStamps[timeStamp].deleteTime(at: row)
self.viewModel.sortTimeStamps()
self.viewModel.timeStamps[timeStamp].times[row] // <- I need this but row is of type IndexSet not Int.
}
}
时间戳记:
struct TimeStamp: Identifiable {
var id = UUID()
var date: Date
var times: [String]
var dayType: String
}
ViewModel:
class SingleEntriesViewModel: ObservableObject {
@Published var timeStamps = [TimeStamp]()
}
答案 0 :(得分:1)
这是因为IndexSet
是类型为Int
的索引的集合。
您可以获取第一个索引:
if let index = row.first {
// index is of type `Int`
// let result = self.viewModel.timeStamps[timeStamp].times[index]
}
或使用forEach
遍历所有索引:
row.forEach { index in
// index is of type `Int`
// let result = self.viewModel.timeStamps[timeStamp].times[index]
}