Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

`.controlSize()` not working after using custom ButtonStyle in SwiftUI

I want to custom some button styles. But after applying them, the .controlSize() modifier will stop working, as shown in below screenshot. Is it possible to support .controlSize() in custom ButtonStyle or some approaches else can bring this control size back?

enter image description here

struct ContentView: View {
    var body: some View {
        VStack {
            
            Button("Hello World") { }
                .buttonStyle(.borderedProminent)
                .controlSize(.regular)
            
            Button("Hello World") { }
                .buttonStyle(CustomButtonStyle())
                .controlSize(.regular)
            
        }
        .padding()
    }
}


struct CustomButtonStyle: ButtonStyle {
    
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .background(Color.cyan)
            .border(Color.brown)
    }
    
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes it is.

You can check the controlSize environment value in your custom style and adjust accordingly. For example:

struct CustomButtonStyle: ButtonStyle {

    @Environment(\.controlSize) var controlSize

    // Ideally switch over every value and produce different styles
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .font(controlSize == .large ? .title : .body)
            .background(Color.cyan)
            .border(Color.brown)
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading