按钮叠加层显示在SwiftUI的按钮文本上方

时间:2020-09-30 08:42:09

标签: ios swift swiftui

我的Button需要几个叠加层才能获得所需的样式(描边,阴影等)。

但是,这些叠加层然后会覆盖Button文本。

enter image description here

查看:

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

如何调整视图,使蓝色文本显示在背景上方

1 个答案:

答案 0 :(得分:1)

您可以使用自定义ButtonStyle

  1. 创建自己的形状,并在其顶部添加.overlay(configuration.label)
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)
    }
}

您还可以使用configuration.isPressed自定义按钮按下时的标签行为。

  1. 将其应用于您的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())
    }
}