删除 SwiftUI (WatchKit) 中的圆形按钮背景

Vik*_*lyi 7 ios swift watchkit swiftui

我正在努力删除 SwiftUI 中自定义圆形 Button 元素的背景,其定义如下:

struct NavButton: View {
    var body: some View {
        Button(action: {})
            VStack {
                Text("Button")
            }
            .padding(40)
            .background(Color.red)
            .font(.title)
            .mask(Circle())
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这会在按钮周围产生一个矩形的浅灰色背景,我希望它不显示:

在此处输入图片说明

我试图在按钮上附加一个“背景”修饰符,它表现出非常奇怪的行为:如果它设置为“Color.clear”,则没有效果。但是如果我将它设置为“Color.green”,它确实会按预期改变背景。

将“背景”修饰符设置为“Color.green”的示例:

struct NavButton: View {
        var body: some View {
            Button(action: {})
                VStack {
                    Text("Button")
                }
                .padding(40)
                .background(Color.red)
                .font(.title)
                .mask(Circle())
            }
            .background(Color.green) // has no effect if set to "Color.clear"
        }
    }
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我想知道我是否在这里遗漏了什么?

PS:我使用的是 Xcode 11.1 (11A1027)

39f*_*edy 13

尝试添加.buttonStyle(PlainButtonStyle())按钮本身。

你会有这样的事情:

    Button(action: {}){
        VStack{
            Text("Button")
        }
        .padding(40)
        .background(Color.red)
        .font(.headline)
        .mask(Circle())  
    }
    .buttonStyle(PlainButtonStyle())
Run Code Online (Sandbox Code Playgroud)

  • 这应该被标记为正确答案 (3认同)

LuL*_*aGa 4

声明您自己的 ButtonStyle:

struct RedRoundButton: ButtonStyle {

    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding(40)
            .font(.title)
            .background( Circle()
                .fill(Color.red))
    }

}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

Button("Button") {}
    .buttonStyle(RedRoundButton())
Run Code Online (Sandbox Code Playgroud)