skip to Main Content

Is it possible to transform that text of a label in a SwiftUI button to uppercase using a style?

struct UppercaseButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .makeUppercase() // ?
    }
}

2

Answers


  1. struct UppercaseButtonStyle: ButtonStyle {
        func makeBody(configuration: Configuration) -> some View {
            configuration.label
                .textCase(.uppercase) // <- here
        }
    }
    

    usage:

    struct ContentView: View {
        var body: some View {
            Button("test", action: {})
                .buttonStyle(UppercaseButtonStyle()) // <= here    
        }
    }
    

    enter image description here

    Login or Signup to reply.
  2. The textCase modifier will work directly on your button, e.g.:

    Button("test", action: {})
      .textCase(.uppercase)
    

    However, if you want to wrap this up in a style, it’s better to use a PrimitiveButtonStyle, as this comes with a Configuration object that can be passed into the Button initializer.

    struct UppercaseButtonStyle: PrimitiveButtonStyle {
      func makeBody(configuration: Configuration) -> some View {
        Button(configuration)
          .textCase(.uppercase)
      }
    }
    
    // bonus points - add a shorthand description to match built-in styles
    
    extension PrimitiveButtonStyle where Self == UppercaseButtonStyle {
      static var uppercase = UppercaseButtonStyle()
    }
    
    // usage
    Button("Test") { }
      .buttonStyle(.uppercase)
    

    This means that you don’t need to worry about any other type of configuration on the button, and your style should be able to play nicely with others, e.g.:

    Button("Test", role: .destructive) { }
      .buttonStyle(.borderedProminent)
      .buttonStyle(.uppercase)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search