onTapGesture is working for finger, but not Pencil

Here's a weird one. Do I need to do something different to handle Pencil taps, or is this a bug?


The following code shows a standard `Button`, and a few of custom Views called `SelectButtons`. The `Button` registers a tap with a Pencil or finger, as expected. The `SelectButtons` only work with my finger, on my iPad Pro. The Pencil taps don't register.


struct ContentView: View {
    let nums = [1,2,3]
    @State var selected: Int = 1
    var body: some View {
        VStack {
            Button(action: { print("Test button tapped")}) {
                Text("Test button")
            }
            ForEach(nums, id: \.self) { num in
                HStack {
                    SelectButton(num: num, current: self.$selected)
                    Text("Number \(num)")
                }
            }
        }
    }
}

struct SelectButton: View {
    let num: Int
    @Binding var current: Int
    var isSelected: Bool { current == num }
    var body: some View {
        ZStack {
            Circle().inset(by: 5).stroke()
            Circle().inset(by: 7).fill(isSelected ? Color.blue : Color.clear)
        }.frame(width:40, height:40)
         .onTapGesture {
            print("SelectButton.onTapGesture \(self.num)")
            self.current = self.num
        }
    }
}

Replies

I found the problem and a fix. It appears that the tap target is not the 40x40 ZStack, but rather the 1pt-wide white stroke line inside the ZStack. So I can fix this by adding a white rectangle behind that stroke, inside the ZStack, then the tap target becomes easy to hit again and all is well.

You should also be able to set the contentShape on the ZStack to Rectangle() with the .contentShape(..) modifier.