arrays - 查找 ScrollView 的索引

标签 arrays swift xcode scrollview swiftui

我有一个显示数组项的水平 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/

相关文章:

ios - 为什么 UIBarButtonItem 显示为已禁用?

arrays - 如何在 Swift 中打乱数组?

ios - UISearchController 过滤器 Swift

ios - Xcode-7.0.1 : Presenting view controllers on detached view controllers is discouraged

swift - 从 Realm 数组中查询特定结果

macos - 在 OSX 应用程序中运行终端命令?

ios - 更改系统字体以进行测试

javascript - 使用数组参数签署 OAuth 请求

java - 计数,数组或 HashMap (或集合)哪个更有效

c - 如何使用for循环初始化数组?