Search code examples
iosswiftswiftui

How to extend the width of a button using SwiftUI


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!


Solution

  • 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())