添加 onTapGesture 时,SwiftUI onDelete 无法检测到点击

Col*_*ang 6 xcode ios swiftui

我正在开发一个带有 SwiftUI 列表的 iOS 应用程序。我正在实现 .onDelete 以使用户能够删除行。但是,我发现当我将 .onTapGesture 添加到包含列表的 VStack 视图时,当用户向左滑动行后点击“删除”按钮时,不会调用 onDelete 函数。但是,当用户将行滑动到左侧以删除它时,它仍然有效。似乎 .onTapGesture 会阻止 .onDelete 接收用户输入。怎么解决这个问题呢?

NavigationView {
    VStack(alignment: .leading) {
        List {
            ForEach(things) { thing in
                Text(thing)
            }
            .onDelete(perform: { indexSet in
                things.remove(atOffsets: indexSet)
            })
        }
        .listStyle(SidebarListStyle())
        }
    .onTapGesture {
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一些可以显示我的问题的代码。

小智 0

这可能没用而且很老套,但是...如果您必须有一个可点击的区域,您可以将所有内容放入 ZStack 中,并在列表上放置一个随机视图并使其可点击。然后,您可以设置大量的填充来释放将点击删除按钮的区域,如下所示:

        NavigationView {
        ZStack {
            List {
                ForEach(things, id: \.self) { thing in
                    Text(thing)
                    }
                        .onDelete(perform: { indexSet in
                            things.remove(atOffsets: indexSet)
                        })
                    }
                        .zIndex(2)
                        .listStyle(SidebarListStyle())
            
                Rectangle()
                    .zIndex(3)
                    .fill(Color.red)
                    .padding(.trailing, 80)
                    .allowsHitTesting(true)
                    .onTapGesture {
                        print("Blocking you")
                    }
                }
        }
Run Code Online (Sandbox Code Playgroud)

我输入了颜色,这样你就可以准确地看到你正在工作的位置,上面的代码会给你这样的外观:

列表上的可点击矩形

当您对矩形覆盖的区域感到满意时,您可以将不透明度设置为非常小的值,只需将颜色替换为

.opacity(0.000001)
Run Code Online (Sandbox Code Playgroud)

或者其他的东西。不幸的是,点击不能与 Color.clear 或 hide() 修饰符一起使用。