当用户长按 ScrollView 时,我尝试从 ScrollView 中删除项目。
所以,如果 ScrollView 的项目来自一个简单的数组(名为 post),我设法使用firstIndex(of: item) 完成这个任务!和
ScrollView(.horizontal, content: {
HStack(spacing: 100) {
ForEach(post, id: \.self){ item in
ZStack {
Text(item).onTapGesture {
self.post.remove(at: self.post.firstIndex(of: item)!)
}
}
}
.padding(.leading, 10)
}
})
我现在的情况是,如果我的数组(命名存储)是模型类型:
class DataModel:Identifiable , Codable {
var nameAirport : String
var countryAirport : String
var icaoAirport : String
var metar: String
var taf : String
如何找到要在方法删除时传递的索引? .firstIndex(at: ) 不存在 我只找到 .firstIndex(where:) 但我找不到如何使用它? 知道如何找到这个索引吗?
在我的代码下面?谢谢你帮助我...
ScrollView(.horizontal, showsIndicators: true) {
HStack(spacing: 10) {
ForEach(dm.storage) { item in
VStack {
Text(item.icaoAirport).onLongPressGesture {
self.dm.storage.remove(at: ) //// how can i get index
///
}
}
}
}
}
最佳答案
我认为你可以在不使用任何参数的情况下做到这一点:
Text(item.icaoAirport).onLongPressGesture {
self.dm.storage.remove
}
正常情况下,它应该可以工作。我将此技术与 .onDelete(self.dm.storage.remove)
结合使用。
如果它不起作用,我建议您向模型添加一个 ID。
关于swift - 从 ScrollView 中获取索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58585948/