SwiftUI - 索引集以索引数组

use*_*450 13 arrays swift swiftui

我在 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)
}
Run Code Online (Sandbox Code Playgroud)

我有一个单独的函数 (AdjustProfileRemove(period)),我想用删除的周期作为变量调用它 - 例如,我想在 AdjustProfileRemove(period: theperiodlist.periods[XXX]) 中找到 XXX。有没有一种简单的方法可以做到这一点(我是从 IndexSet 猜测的)还是我错过了一些基本的东西?

谢谢。

use*_*734 13

.onDelete 被声明为

@inlinable public func onDelete(perform action: ((IndexSet) -> Void)?) -> some DynamicViewContent
Run Code Online (Sandbox Code Playgroud)

IndexSet 只是数组中要删除的元素的所有索引的集合。让我们试试这个例子

var arr = ["A", "B", "C", "D", "E"]
let idxs = IndexSet([1, 3])

idxs.forEach { (i) in
    arr.remove(at: i)
}
print(arr)
Run Code Online (Sandbox Code Playgroud)

所以结果 arr 现在是

["A", "C", "D"]
Run Code Online (Sandbox Code Playgroud)

.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)
Run Code Online (Sandbox Code Playgroud)

它现在按您的预期工作,是吗?现在的结果是

["A", "C", "E"]
Run Code Online (Sandbox Code Playgroud)

基于

theperiodlist.periods.remove(atOffsets: offsets)
Run Code Online (Sandbox Code Playgroud)

看来,ThePeriodList已经具有所需功能的内置功能。

在你的情况下只需更换

AdjustProfileRemove(period: theperiodlist.periods[XXX])
Run Code Online (Sandbox Code Playgroud)

offsets.sorted(by: > ).forEach { (i) in
    AdjustProfileRemove(period: theperiodlist.periods[i])
}
Run Code Online (Sandbox Code Playgroud)