10

Using Xcode beta 6 and SwiftUI, creating a Text view using a >localized< string, how can I uppercase it without having to make the localized string value uppercased? I guess I want a ViewModifier for changing case, but it does not seem to exist?

Text("SignIn.Body.Instruction".uppercased()) will uppercase the localization key, so that will not work, as instructed in this SO question about uppercasing a non-localized string.

Sajjon
  • 8,938
  • 5
  • 60
  • 94
  • Does localizedCapitalized not work ? https://developer.apple.com/documentation/foundation/nsstring/1414885-localizedcapitalized#declarations – yawnobleix Aug 20 '19 at 14:14
  • @yawnobleix that is a completely different thing :D. This is a `SwiftUI` question. We _cannot_ change the string itself because it is referring to the name of a _key_. – Sajjon Aug 20 '19 at 14:25

3 Answers3

15

It is now possible with all new textCase ViewModifier (Xcode 12 Beta 3), like so:

Text("SignIn.Body.Instruction")
    .textCase(.uppercase)

Or lowercase:

Text("SignIn.Body.Instruction")
    .textCase(.lowercase)
Sajjon
  • 8,938
  • 5
  • 60
  • 94
11

How about using the smallCaps modifier for Font? E.g., Text("Hello World").font(Font.body.smallCaps()) will render "HELLO WORLD", but the underlying string will retain its proper localized capitalization for the purposes of accessibility.

marcprux
  • 9,845
  • 3
  • 55
  • 72
0

Localise it manually and then uppercase it.

extension String {
    func toUpperCase() -> String {
        return localized.uppercased(with: .current)
    }
    private var localized : String {
        return NSLocalizedString( self, comment:"")
    }
}

Text("SignIn.Body.Instruction".toUpperCase())
Hocine B
  • 391
  • 2
  • 8
Brett
  • 1,647
  • 16
  • 34
  • `NSLocalizedString( self, comment:"")` not a good idea, because the key argument to NSLocalizedString is not constant. Thus genstrings and Xcode Editor -> Export for Localization cannot pick it up. Short term it may be convenient, but it will bite you when later you have to find all strings to localise in the app manually! – guru_meditator Jan 31 '20 at 12:01
  • 1
    You don't want to use uppercased(), that is meant for programmatic strings, not user-facing strings, as it does not take into account locale. See `.uppercased(with: Locale.current))` – guru_meditator Jan 31 '20 at 12:03
  • I didn't know about .uppercased(with: Locale.current)) thanks for the tip. As for the issue with genstrings your point is quite valid, however in SwiftUI I hope to not have to use my method very often, mostly the localisation will be handled by Text() automatically. – Brett Feb 02 '20 at 23:06