Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove circular button background in SwiftUI (WatchKit)

I'm struggling to remove the background of a custom circular Button element in SwiftUI which is defined as follows:

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

This results in a rectangular light gray background around the button, where I want it to not be shown:

enter image description here

I tried to append a "background" modifier to the button, and it demonstrates very strange behavior: if it's set to "Color.clear", there is no effect. But if I set it to "Color.green" it does change the background as expected.

Example of setting the "Background" modifier to "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"
        }
    }

enter image description here

I wonder if I'm missing something here?

PS: I'm using Xcode 11.1 (11A1027)

like image 424
Viktor Malyi Avatar asked Oct 07 '19 11:10

Viktor Malyi


2 Answers

Try adding .buttonStyle(PlainButtonStyle()) on the button itself.

You would have something like this:

    Button(action: {}){
        VStack{
            Text("Button")
        }
        .padding(40)
        .background(Color.red)
        .font(.headline)
        .mask(Circle())  
    }
    .buttonStyle(PlainButtonStyle())
like image 172
39fredy Avatar answered Sep 28 '22 04:09

39fredy


Declare your own ButtonStyle:

struct RedRoundButton: ButtonStyle {

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

}

and then use it like this:

Button("Button") {}
    .buttonStyle(RedRoundButton())
like image 28
LuLuGaGa Avatar answered Sep 28 '22 04:09

LuLuGaGa