9

I cannot figure out how to change the width of buttons in SwiftUI.

I have already attempted: using .frame(minWidth: 0, maxWidth: .infinity), using Spacer() around the button and navigationlink, using frame on the Text field and padding on the button, look through the documentation, as well as a few other things I found while just searching online. However nothing changes the buttons width whatsoever.

NavigationLink(destination: Home(), isActive: self.$isActive) { Text("") } Button(action: { self.isActive = true }) { LoginBtn() } struct LoginBtn: View { var body: some View { Text("Login") .fontWeight(.bold) .padding() .foregroundColor(Color.white) .background(Color.orange) .cornerRadius(5.0) } } 

Photo of current button

I would like to have the button to extend to be similar to the width of the TextFields used. Again, I know there have been answers posted but for some reason I cannot get mine to work. Thanks!

2 Answers 2

12

I like this approach since it lets me use the default button style, but still results in a wider button.

Button(action: { // Whatever button action you want. }, label: { Text("Okay") .frame(maxWidth: .infinity) }) .buttonStyle(.automatic) 
Sign up to request clarification or add additional context in comments.

Comments

11

Declare your own button style:

struct WideOrangeButton: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .padding() .frame(minWidth: 0, maxWidth: .infinity) .foregroundColor(.white) .padding() .background( RoundedRectangle(cornerRadius: 5.0).fill(Color.orange) ) } } 

and then use it like this:

Button(action: { self.isActive = true }) { Text("Login") .fontWeight(.bold) } .buttonStyle(WideOrangeButton()) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.