Home > Mobile >  How to make SwiftUI button label uppercase
How to make SwiftUI button label uppercase

Time:11-08

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() // ?
    }
}

CodePudding user response:

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

CodePudding user response:

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)
  • Related