Search code examples
macosswiftuiswiftui-button

macOS SwiftUI Button "Active Area" Width of Parent View


For a macOS app, I like to extend a button's width across it's parent view using SwiftUI. I tried this: import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Button(action: {print("TEST")}) {
                Image(systemName: "clock")
                    .frame(width: 25, height: 25, alignment: .center)
                Text("This is a button")
                    .frame(minWidth: 200, idealWidth: 200, maxWidth: .infinity, minHeight: 25, idealHeight: 25, maxHeight: 25, alignment: .leading)
                Image(systemName: "chevron.left")
                    .frame(width: 25, height: 25, alignment: .center)
            }
            .buttonStyle(PlainButtonStyle())
        }
    }
}

and it will yield a result that looks quite what I am searching, but if you click in the area marked in red in the following screenshot of the app

enter image description here

the buttons action does not fire. Also the area between the first image and the text does not fire the action. I also tried to implement a custom ButtonStyle but with no luck. How can I achieve a button that extends over the full width of the parent view?


Solution

  • You can try using .contentShape(Rectangle()):

    Button(action: { print("TEST") }) {
        HStack {
            // ...
        }
        .frame(maxWidth: .infinity)
        .contentShape(Rectangle())
    }