首页 > 解决方案 > SwiftUI 中的按钮大小和颜色

问题描述

我是 SwiftUI 和 iOS 开发的新手。

我尝试创建 2 个按钮,但无法更改背景颜色或大小。

它看起来像这样:

在此处输入图像描述

下面是代码:

        HStack {
            Button( action: {
                print("click")
            }){
                Text("Login")
                    .foregroundColor(.purple)
                    .padding()
                    .overlay(
                        RoundedRectangle(cornerRadius: 20)
                            .stroke(Color.purple, lineWidth: 1)
                    )
            }
            Button( action: {
                print("click")
            }){
                Text("Register")
                    .foregroundColor(.white)
                    .padding()
                    .overlay(
                        RoundedRectangle(cornerRadius: 20)
                            .stroke(Color.black, lineWidth: 1)
                            
                    )
                
            }
        }

我正在寻找一个按钮,它几乎使用了屏幕的一半,每边的边距为 10px。目标是让 2 个按钮几乎覆盖显示屏的宽度。我也试着让它更薄。上下边框之间的距离太大,当左右边框必须更宽时,我希望它靠近文本。

我也不知道如何将按钮背景颜色更改为黑色

任何想法 ?

谢谢

标签: iosswiftswiftui

解决方案


您可以创建自己的ButtonStyle,您可以完全自定义和重用

struct CustomButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding(10) // *make it thinner*
            .frame(maxWidth: .infinity) // expand horizontally 
            .foregroundColor(.purple)
            .background(
                Rectangle()
                    .stroke(Color.purple, lineWidth: 1)
                    .background(Color.black) // *change the button background color to black*
                    .cornerRadius(20)
            )
            .padding(.horizontal, 10) // *margin of 10px on each side*
            .opacity(configuration.isPressed ? 0.7 : 1)
    }
}
struct ContentView: View {
    var body: some View {
        HStack {
            Button("Login") {
                print("click")
            }
            .buttonStyle(CustomButtonStyle())
            Button("Register") {
                print("click")
            }
            .buttonStyle(CustomButtonStyle())
        }
    }
}

推荐阅读