我在 NavigationView 和 list 中使用 ForEach 并结合用户使用 .onDelete() 删除一行时调用的函数,如下所示。
struct PeriodListView: View {
@ObservedObject var theperiodlist = ThePeriodList()
@EnvironmentObject var theprofile: TheProfile
@State private var showingAddPeriod = false
var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}
var body: some View {
NavigationView {
List {
ForEach(theperiodlist.periods) {period in
PeriodRow(period: period)
}
.onDelete(perform: removePeriods)
}
.navigationBarTitle("Periods")
.navigationBarItems(trailing:
Button(action: {self.showingAddPeriod = true}) {
Image(systemName: "plus")
}
)
.sheet(isPresented: $showingAddPeriod) {
AddPeriod(theperiodlist: self.theperiodlist).environmentObject(self.theprofile)
}
}
}
func removePeriods(at offsets: IndexSet) {
AdjustProfileRemove(period: theperiodlist.periods[XXX])
theperiodlist.periods.remove(atOffsets: offsets)
}
我有一个单独的函数 (AdjustProfileRemove(period)),我想用删除的周期作为变量来调用它 - 例如我想在 AdjustProfileRemove(period: theperiodlist.periods[XXX]) 中找到 XXX。有没有一种简单的方法可以做到这一点(我是从 IndexSet 猜测的)还是我错过了一些基本的东西?
谢谢。
最佳答案
.onDelete 被声明为
@inlinable public func onDelete(perform action: ((IndexSet) -> Void)?) -> some DynamicViewContent
IndexSet 只是数组中要删除的元素的所有索引的集合。让我们试试这个例子
var arr = ["A", "B", "C", "D", "E"]
let idxs = IndexSet([1, 3])
idxs.forEach { (i) in
arr.remove(at: i)
}
print(arr)
所以结果 arr 现在是
["A", "C", "D"]
.onDelete 之所以使用IndexSet,是因为可以选择List 中不止一行进行删除操作。
小心! 看到结果数组!实际上一个一个地删除元素需要一些逻辑......
让我们试试
var arr = ["A", "B", "C", "D", "E"]
let idxs = IndexSet([1, 3])
idxs.sorted(by: > ).forEach { (i) in
arr.remove(at: i)
}
print(arr)
它现在按您的预期工作,是吗?现在的结果是
["A", "C", "E"]
基于
theperiodlist.periods.remove(atOffsets: offsets)
看来,
ThePeriodList
已经具有具有所需功能的内置功能。在你的情况下只需更换
AdjustProfileRemove(period: theperiodlist.periods[XXX])
与
offsets.sorted(by: > ).forEach { (i) in
AdjustProfileRemove(period: theperiodlist.periods[i])
}
关于arrays - SwiftUI - 索引集以索引数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59868180/