通过自定义ButtonStyle统一App内的按钮样式


2年前 745次点击 来自 移动端

标签: SwiftUI

SwiftUI提供了ButtonStyle的协议,用于自定义Button的样式,统一App内按钮的视觉效果并方便根据主题更改样式。

以下是一个自定义渐变背景色样式:

struct GradientBackgroundStyle: ButtonStyle {
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .frame(minWidth: 0, maxWidth: .infinity)
            .padding()
            .foregroundColor(.white)
            .background(LinearGradient(gradient: Gradient(colors: [Color.purple, Color.pink]), startPoint: .leading, endPoint: .trailing))
            .cornerRadius(20)
            .padding(.horizontal, 10)
            .scaleEffect(configuration.isPressed ? 0.9 : 1.0)
    }
}

调用buttonStyle方法应用于Button:

struct ButtonSytleView: View {
    var body: some View {
        VStack {
            Text("自定义Button样式")

            Button(action: {
                print("删除按钮!")
            }) {
                HStack {
                    Image(systemName: "trash")
                        .font(.title)
                    Text("删除")
                        .fontWeight(.semibold)
                        .font(.title)
                }
            }
            .buttonStyle(GradientBackgroundStyle())
        }
    }
}

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1