我有一个显示数组项的水平 ScrollView 。
如何读取用户长按的 ScrollView 的索引。
使用 .onLongPressGesture {"action to be perform"} 我如何读取要在我的函数中传递的索引以删除项目。
ScrollView(.horizontal, content: {
HStack(spacing: 100) {
ForEach(post, id: \.self){ item in
ZStack {
Rectangle().foregroundColor(.blue).frame(width: 190, height: 170, alignment: .center)
Text(item)
}.onTapGesture {
self.temp = item
}
.onLongPressGesture {
// find index
//perform delate at index
//pass the index to the function delate
self.delate(index: 0)
}
}
}
.padding(.leading, 10)
})
如果我手动写入索引 0,延迟工作正常,但我想传递用户长按的索引。 感谢您的帮助。
最佳答案
试试这个:(更好的是你不必使用索引,你可以使用项目本身)
struct ContentView: View {
@State var post = ["test2", "test3", "test4"]
var body: some View {
ScrollView(.horizontal, content: {
HStack(spacing: 100) {
ForEach(post, id: \.self){ item in
VStack {
Rectangle().foregroundColor(.blue).frame(width: 190, height: 170, alignment: .center)
Text(item).onTapGesture {
// post.remove(at: post.index(item))
self.post.remove(at: self.post.index(of: item)!)
}
}
}
.padding(.leading, 10)
}
})
}
}
关于arrays - 查找 ScrollView 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58579539/