Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase the size of a Button in SwiftUI? (Multiplatform project)

Tags:

swiftui

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/

tap problem

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:

enter image description here

Button(action: {}, label: {
           Text("Click me")
                    .frame(width: 100, height: 100)
                    .background(Color.yellow)
        })
like image 218
kiatra Avatar asked Nov 27 '25 07:11

kiatra


2 Answers

Here is a possible solution

For iOS

enter image description here

 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()
    }
}
like image 111
Seungjun Avatar answered Nov 28 '25 21:11

Seungjun


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())
like image 30
kiatra Avatar answered Nov 28 '25 22:11

kiatra