I am trying to increase the size oaf a Button in SwiftUI, Xcode 12.5 in a Multiplatform project:
Button("Click me") {
// Perform action here
}
.frame(width: 100, height: 100)
.background(Color.yellow)
.buttonStyle(BorderlessButtonStyle())
After checking the API I found that I can style the button but I can not figure out how to make the click box larger. So that the entire yellow frame receives the click action not just the label.
Edit:
The The tap area problem is explained well here: https://alejandromp.com/blog/playing-with-swiftui-buttons/

But the solution there to change add an element to the button and change the size of that does only work in an iOS project. In a Multiplatform project the frame of the button has the wrong size:

Button(action: {}, label: {
Text("Click me")
.frame(width: 100, height: 100)
.background(Color.yellow)
})
Here is a possible solution
For iOS

Button(action: {
//add actions at here
}) {
VStack {
Text("Name")
}.frame(width: 100, height: 100)
.background(Color.yellow)
.cornerRadius(20)
}
For macOS (macOS version works well for iOS version too)
struct ContentView: View {
var body: some View {
VStack{
Button(action: {
//add actions at here
}) {
VStack {
Text("Button Name")
}.frame(width: 100, height: 100)
.background(Color.yellow)
.cornerRadius(20)
}.buttonStyle(CustomButtonStyle())
}
}
}
struct CustomButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.foregroundColor(Color.blue)
.cornerRadius(10.0)
.padding()
}
}
I have found this solution where adding contentShape seems to do the trick:
Button(action: doSomething) {
Text("Click me")
.frame(width: 100, height: 100)
.contentShape(Rectangle())
}
.background(Color.yellow)
.buttonStyle(PlainButtonStyle())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With