简体   繁体   中英

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.

在此处输入图片说明

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?

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())
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM