Arrays 查找滚动视图的索引
我有一个显示数组项的水平滚动视图 如何读取用户长按滚动视图的索引 使用.onLongPress手势{“要执行的操作”}如何读取要在函数中传递的索引以对项目进行挖掘Arrays 查找滚动视图的索引,arrays,swift,xcode,scrollview,swiftui,Arrays,Swift,Xcode,Scrollview,Swiftui,我有一个显示数组项的水平滚动视图 如何读取用户长按滚动视图的索引 使用.onLongPress手势{“要执行的操作”}如何读取要在函数中传递的索引以对项目进行挖掘 ScrollView(.horizontal, content: { HStack(spacing: 100) { ForEach(post, id: \.self){ item in
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,delate工作正常,但我希望通过用户长按的索引。
感谢您的帮助。试试这个:(更好的是,您不必使用索引,只需使用项目本身即可)
我认为正确的方法是在开始时获取索引,而不是在ViewBuilder中:
ForEach(Array(post.enumerated()), id: \.element){ (index, element) in
....
}
完整视图如下所示:
struct ScrollViewHStackView: View{
@State private var post = ["1","2","3","4","5"]
@State private var temp : String = ""
func delete(index: Int){
self.post.remove(at: index)
}
var body: some View {
ScrollView(.horizontal, content: {
//HStack(spacing: 100) {
HStack{
ForEach(Array(post.enumerated()), id: \.element){ (index, element) in
ZStack {
Rectangle().foregroundColor(.blue).frame(width: 190, height: 170, alignment: .center)
Text(element)
}.onTapGesture {
self.temp = element
}
.onLongPressGesture {
// find index
//perform delate at index
//pass the index to the function delate
self.delete(index: index)
}
}}
// }
.padding(.leading, 10)
})}}
struct ScrollViewHStackView: View{
@State private var post = ["1","2","3","4","5"]
@State private var temp : String = ""
func delete(index: Int){
self.post.remove(at: index)
}
var body: some View {
ScrollView(.horizontal, content: {
//HStack(spacing: 100) {
HStack{
ForEach(Array(post.enumerated()), id: \.element){ (index, element) in
ZStack {
Rectangle().foregroundColor(.blue).frame(width: 190, height: 170, alignment: .center)
Text(element)
}.onTapGesture {
self.temp = element
}
.onLongPressGesture {
// find index
//perform delate at index
//pass the index to the function delate
self.delete(index: index)
}
}}
// }
.padding(.leading, 10)
})}}