首页 > 解决方案 > SwiftUI 按钮大小/形状/颜色不变

问题描述

我正在尝试使用 SwiftUI 为 MacOS 应用程序制作自定义按钮,但是,我似乎无法调整按钮区域的大小,并且按钮的颜色似乎无法更改。我在网上找到的所有示例都说使用 .frame 或 .padding 来设置宽度和高度,但这不会改变按钮的形状。有没有其他人在开发 MacOS 应用程序时遇到过这种情况?此处的按钮图片

struct customButton: View {
    var body: some View {

        Button(action: {
            print("Delete button tapped!")
        }) {
            HStack {
                Image(systemName: "trash")
                    .resizable()
                    .scaledToFit()
                    .imageScale(.large)
                Text("Delete")
            }
            .padding()
            .background(
                Capsule().strokeBorder(Color.white, lineWidth: 1.25)
            )
        }
        .accentColor(Color.white)
        
    }
}

标签: swiftmacosswiftui

解决方案


您必须使用.buttonStyle(PlainButtonStyle())摆脱默认按钮 UI。

Button(action: {
    print("Delete button tapped!")
}) {
    HStack {
        Image(systemName: "trash")
            .resizable()
            .scaledToFit()
            .imageScale(.large)
        Text("Delete")
    }
    .padding()
    .background(
        Capsule().strokeBorder(Color.white, lineWidth: 1.25)
    )
}
.accentColor(Color.white)
.buttonStyle(PlainButtonStyle())

推荐阅读