buttonswiftui

How do I create a ButtonStyle with a a larger image?


I’m trying to create a ButtonStyle for an application. I can find plenty of examples, but I can’t get much actual detail.

Here is a simple example:

struct SpecialButton: ButtonStyle {
    func makeBody(configuration: ButtonStyleConfiguration) -> some View {
        configuration.label
            .font(.system(size: 10, weight: .bold))
            .imageScale(.large)
    }
}

The .imageScale() value appears to be limited to one of three sizes, but the .large value is still smaller that I would have liked, and I would have liked a larger image size.

Is there a way to do this in a ButtonStyle?


Solution

  • You can define a LabelStyle to style the label the way you want it:

    struct SpecialLabel: LabelStyle {
        func makeBody(configuration: Configuration) -> some View {
            HStack {
                configuration.icon
                    .font(.largeTitle)
                configuration.title
                    .font(.system(size: 10, weight: .bold))
            }
        }
    }
    

    Of course, you could use a VStack if preferred.

    Then use the special label style inside your custom ButtonStyle:

    struct SpecialButton: ButtonStyle {
        func makeBody(configuration: ButtonStyleConfiguration) -> some View {
            configuration.label
                .labelStyle(SpecialLabel())
        }
    }
    

    Example use:

    Button("Delete", systemImage: "trash") {}
        .buttonStyle(SpecialButton())
    

    Screenshot