为什么SwiftUI onTapGesture不总是有效

时间:2020-07-29 13:33:28

标签: swiftui gesture-recognition

SWiftUI中的onTapGesture无法可靠运行。此示例显示了问题,即有时您在点击一个单元格时,背景会变为应有的灰色,而下一次相邻单元格发生了变化,而其他时间则什么也没有发生。有什么想法吗?

struct ContentView: View {
    @State var cellFg: [[Color]] = [
        [.clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear],
        [.clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear],
        [.clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear],
        [.clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear],
        [.clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear],
        [.clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear],
        [.clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear],
        [.clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear],
        [.clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear, .clear]
    ]
    
    var body: some View {
        VStack {
            Spacer()
            ForEach(0..<9) { row in
                HStack {
                    Spacer()
                    ForEach(0..<9) { column in
                        Rectangle()
                            .foregroundColor(cellFg[row][column])
                            .border(Color.gray, width: 1)

                            // When you tap, it sometimes works, sometimes selects
                            // an adjacent cell and sometimes does nothing
                            .onTapGesture {
                                print("Row \(row) - Column\(column)")
                                cellFg[row][column] = .gray
                            }
                    }
                    Spacer()
                }
            }
            Spacer()
        }
    }
}

2 个答案:

答案 0 :(得分:4)

默认情况下,矩形是透明的,但手势要求内容不透明。

这是一个修复程序(已通过Xcode 11.4 / iOS 13.4测试)

Rectangle()
    .foregroundColor(self.cellFg[row][column])
    .border(Color.gray, width: 1)
    .contentShape(Rectangle())         // << here !!

.contentShape使得整个帧的可测试性都不受透明度影响。

答案 1 :(得分:0)

添加一个扩展来解决这个问题

private struct ExpandAreaTap: ViewModifier {
    func body(content: Content) -> some View {
        ZStack {
            Rectangle()
                .foregroundColor(Color.white)
                .contentShape(Rectangle())
            content
        }
    }
}

extension View {
    func expandTap(tap: @escaping () -> ()) -> some View {
        self.modifier(ExpandAreaTap()).onTapGesture(perform: tap)
    }
}