繁体   English   中英

SwiftUI - 索引集以索引数组

[英]SwiftUI - Indexset to index in array

我在 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])
}

这是可能的方法(考虑到通常offsets可以包含许多索引)

func removePeriods(at offsets: IndexSet) {
    theperiodlist.periods = 
        theperiodlist.periods.enumerated().filter { (i, item) -> Bool in
            let removed = offsets.contains(i)
            if removed {
                AdjustProfileRemove(period: item)
            }
            return !removed
        }.map { $0.1 }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM