Zorgan
Zorgan

Reputation: 9153

Button overlay is showing over Button Text, SwiftUI

My Button requires a couple overlays to get the style it needs (stroke, shadow etc).

However these overlays then go over the Button text.

enter image description here

View:

struct ProfileTest: View {
    var body: some View {
        Button(action: {
        }){
            HStack {
                Text("OFFLINE")
                    .font(.custom("Seravek-Bold", size: 25))
                    .fontWeight(.bold)
                    .foregroundColor(Color.blue)
            }
        }.padding(EdgeInsets(top: 12, leading: 15, bottom: 12, trailing: 15))
        .cornerRadius(50)
        .overlay(
            RoundedRectangle(cornerRadius: 50)
                .stroke(Color.black, lineWidth: 1)
        )
        .overlay(
            RoundedRectangle(cornerRadius: 50)
                .fill(Color.red)
                .shadow(color: Color.black.opacity(1), radius: 1)
        )
        .opacity(0.7)
        .padding(.bottom, 100)
        .padding(.bottom, 20)
    }
}

How can I adjust my view so that the blue text shows above the background?

Upvotes: 2

Views: 4627

Answers (1)

pawello2222
pawello2222

Reputation: 54611

You can use a custom ButtonStyle.

  1. Create your own shape and add .overlay(configuration.label) on top of it:
struct CustomButtonStyle: ButtonStyle {
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .hidden()
            .padding(EdgeInsets(top: 12, leading: 15, bottom: 12, trailing: 15))
            .cornerRadius(50)
            .overlay(
                RoundedRectangle(cornerRadius: 50)
                    .stroke(Color.black, lineWidth: 1)
            )
            .overlay(
                RoundedRectangle(cornerRadius: 50)
                    .fill(Color.red)
                    .shadow(color: Color.black.opacity(1), radius: 1)
            )
            .opacity(0.7)
            .overlay(configuration.label)
            .padding(.bottom, 100)
            .padding(.bottom, 20)
    }
}

You can also use configuration.isPressed to customise your label behaviour on button press.

  1. Apply it to your Button:
struct ContentView: View {
    var body: some View {
        Button(action: {}) {
            HStack {
                Text("OFFLINE")
                    .font(.custom("Seravek-Bold", size: 25))
                    .fontWeight(.bold)
                    .foregroundColor(Color.blue)
            }
        }
        .buttonStyle(CustomButtonStyle())
    }
}

Upvotes: 2

Related Questions