arrays - SwiftUI - 索引集以索引数组

标签 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)
}

我有一个单独的函数 (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/

相关文章:

SwiftUI tabview(滚动)事件?

c++ - 奇怪的数组行为

c++ - 在固定的、无序的、拥有的数组中安全、惯用的销毁和压缩

javascript - 如何在 JavaScript 中的对象内添加数组连接方法?

ios - 在 Swift 中将 PEM 响应转换为 PCKS12 数据

ios - Realm 不持久写入所做的更改

ios - 如何 'pop' 导航 Controller 及其所有 View Controller

javascript - 使用javascript的reduce方法将对象数组转换为每年和每月

swift - 为什么 SwiftUI Limited `@ViewBuilder` 参数计数为 10?

ios - 在点击期间格式化 TextField 文本