简体   繁体   中英

How to make SwiftUI Buttons a fixed size?

I am trying to create 2 buttons of equal size, but the size is determined by the text inside the button. The two buttons are "login" and "create account", so the "create account" button is larger. I tried to use.frame() to adjust the size, but that just made it have extra padding around it.

Here is my code:

 HStack {
                    Button(action: {
                        print("Login button pressed")
                    }) {
                    Text("Login")
                        .padding()
                        .foregroundColor(Color.white)
                        .background(Color(UIColor.buttonColor))
                        .cornerRadius(15)
                    
                        
                    }
                    
                    Button(action: {
                        print("Create Account button pressed")
                    }) {
                    Text("Create Account")
                        .padding()
                        .foregroundColor(Color.white)
                        .background(Color(UIColor.buttonColor))
                        .cornerRadius(15)
                    }
                }

And here is what that displays

纽扣

Best to make a button style you can use across your app which will also ensure any future stack is proportionally filled. Otherwise you'll find your UIs will get messy making Buttons with Text()s like that.

Laying out the buttons with a custom Style in the HStack:

 HStack(spacing: 20) {
     Button("Login", action: { print("login")})
            .buttonStyle(PrimaryButtonStyle())
     Button("Create Account", action: { print("create account")})
            .buttonStyle(PrimaryButtonStyle())
    }.padding([.leading, .trailing], 10)

PrimaryButtonStyle:

struct PrimaryButtonStyle: ButtonStyle {

var backgroundColor: Color = .black
var textColor: Color = Color.white
var height: CGFloat = 46
var cornerRadius: CGFloat = 15
var fontSize: CGFloat = 15
var disabled: Bool = false
var textSidePadding: CGFloat = 30
var weight: Font.Weight = .semibold

func makeBody(configuration: Configuration) -> some View {
    configuration.label
        .padding([.leading, .trailing], textSidePadding)
        .frame(maxWidth: .infinity, maxHeight: height)
        .background(disabled ? .gray : backgroundColor)
        .foregroundColor(textColor)
        .cornerRadius(cornerRadius)
        .font(.system(size: fontSize, weight: weight, design: .default))
        .scaleEffect(configuration.isPressed ? 1.2 : 1)
        .animation(.easeOut(duration: 0.2), value: configuration.isPressed)
    }
}

Result:

在此处输入图像描述 :

.frame and set width to UI screen - blank should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM