Home > Enterprise >  SwiftUI button hittable outside image?
SwiftUI button hittable outside image?

Time:07-10

I have a button in SwiftUI (macOS) defined like this:

      Button(action: { print("hit") },
             label: { Image(systemName: "minus") })
        .frame(width: 21, height: 21)
        .contentShape(Rectangle())
        .buttonStyle(.plain)

When I select the button in the preview, the green highlight rectangle shows the expected square shape for the button. But only the image itself is actually clickable, and that minus sign is hard to hit. I thought .contentShape(Rectangle()) would fix that, but it doesn't seem to have any effect, either before or after .frame().

How do I make the button's entire frame area clickable?

CodePudding user response:

Instead of set external frame (which adds space "around" button), move it inside, to content, which will "increase" the button, like

  Button(action: { print("hit") },
         label: { 
           Image(systemName: "minus") 
              .frame(width: 21, height: 21)    // << here !!
              .contentShape(Rectangle())       // << add this !!
         })
    .buttonStyle(.plain)

Tested with Xcode 13.4 / macOS 12.4

  • Related