【问题标题】:Remove circular button background in SwiftUI (WatchKit)删除 SwiftUI (WatchKit) 中的圆形按钮背景
【发布时间】:2019-10-07 11:53:11
【问题描述】:

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

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

这会导致按钮周围出现矩形浅灰色背景,我希望它不显示:

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

将“Background”修饰符设置为“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"
        }
    }

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

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

【问题讨论】:

  • 尝试调整按钮的框架以适应圆形大小,而不是隐藏按钮的背景颜色。

标签: ios swift watchkit swiftui


【解决方案1】:

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

你会有这样的东西:

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

【讨论】:

  • 这应该被标记为正确答案
【解决方案2】:

声明你自己的ButtonStyle:

struct RedRoundButton: ButtonStyle {

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

}

然后像这样使用它:

Button("Button") {}
    .buttonStyle(RedRoundButton())

【讨论】:

  • 谢谢,但这不会改变任何事情。
  • 这在 watchOS 应用中对我来说效果很好。
【解决方案3】:

试试这个:

struct ContentView: View {
    var body: some View {
        Button(action: {}) {
            Text("Button")
            .frame(width: 80, height: 80)
        }
        .background(Color.red)
        .cornerRadius(40)
        .frame(width: 80, height: 80)
    }
}

【讨论】:

  • 感谢您的回答,但框架的宽度和高度值与拐角半径之间存在依赖关系。
【解决方案4】:

试试这个。

struct ContentView: View {
    var body: some View {
        VStack {
                Button(action: {}){
                    Text("button")
                        .font(.system(size: 50))
                        .foregroundColor(.black)
                        .bold()
                    
                }
                        .padding(30)
                        .background(Color.yellow)
                        .font(.headline)
                        .mask(Circle())
                        .buttonStyle(PlainButtonStyle())
        } // end Vstack
         
    }// end body
}


【讨论】:

    猜你喜欢
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2014-10-20
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    相关资源
    最近更新 更多