Question

How to force UILabel to draw a text with upper case chars?

Was it helpful?

Solution

Objective-C

NSString *text = @"Hello";
[myLabel setText:[text uppercaseString]];

Swift 3 & 4

let text = "Hello"
myLabel.text = text.uppercased()

OTHER TIPS

You were asking if there might be an equivalent to the CSS declaration text-transform: uppercase; for attributed text in iOS. Unfortunately this is not available, and I agree that it could be convenient to add an attribute for this.

I've personally subclassed UILabel, added an uppercase boolean property, and overridden the text setter so that it will automatically call uppercaseString on the new value if uppercase is set to true.

This is the Swift 3 & Swift 4 version:

titleLabel.text = titleLabel.text?.uppercased()

If you wish to force a string to display in all Uppercase characters in Swift here is my code that works great for me.

titleLabel.text = youStringVariable.uppercaseString 

A quick look into the documentation would have been quicker.

NSString *upperCase = [string uppercaseString];

Instead of changing the text to be uppercase, you can use an uppercase / small-caps font.

titleLabel.font = .smallCapsSystemFont(ofSize: 17, weight: semibold)
extension UIFont {
    
  static func smallCapsSystemFont(ofSize size: CGFloat, weight: Weight) -> UIFont { 
    // Upper case letters are in small caps
    let upperCaseFeature: [UIFontDescriptor.FeatureKey: Int] = [
      .type: kUpperCaseType,
      .selector: kUpperCaseSmallCapsSelector
    ]

    // Lower case letters are in small caps
    let lowerCaseFeature: [UIFontDescriptor.FeatureKey: Int] = [
      .type: kLowerCaseType,
      .selector: kLowerCaseSmallCapsSelector
    ]

    let features = [upperCaseFeature, lowerCaseFeature]
    let descriptor = UIFont.systemFont(ofSize: size, weight: weight)
      .fontDescriptor
      .addingAttributes([.featureSettings: features])

    return UIFont(descriptor: descriptor, size: size)
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top