Search code examples
arraysswiftxcodescrollviewswiftui

Find a index of a scroll View


i have a horizontal scrollView that display the item of an array.

how can i read the index of the scroll view where the user long press.

using .onLongPressGesture {"action to be perform"} how can i read the index to be pass at my function to delate the item.

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

the delate working fine if i write manually the index 0, but i want to pass the index where the user long Press. thanks for the help.


Solution

  • try this: (and even better you don't have to work with index, you just can work with the item itself)

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