13

Currently, I am changing the font of the navigation bar using the following in the AppDelegate:

[[UINavigationBar appearance] setTitleTextAttributes:
 [NSDictionary dictionaryWithObjectsAndKeys:
  [UIFont fontWithName:@"..." size:...], NSFontAttributeName,
  nil]];

Is there a way to do the same to make sure that the string is capitalized globally?

p0lAris
  • 4,750
  • 8
  • 45
  • 80

3 Answers3

3

It's not possible to achieve this using NSAttributedString, but instead you can change the title in your base view controller class. Try this:

/// Base class for all view controllers
class BaseViewController: UIViewController {

    private var firstWillAppearOccured = false

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if !firstWillAppearOccured {
            viewWillFirstAppear(animated)
            firstWillAppearOccured = true
        }
    }

    /// Method is called when `viewWillAppear(_:)` is called for the first time
    func viewWillFirstAppear(_ animated: Bool) {
        title = title?.uppercased() // Note that title is not available in viewDidLoad()
    }
}
boa_in_samoa
  • 587
  • 7
  • 16
1

You can configure the UIFont used by the UINavigationBar appearance to use caps.

extension UIFont {

func getAllCapsFont(with size: CGFloat, andWeight weight: Weight) -> UIFont {
    let fontDescriptor = UIFont.systemFont(ofSize: size, weight: weight).fontDescriptor
    
    let upperCaseFeature: [UIFontDescriptor.FeatureKey: Int] = [
        .featureIdentifier: kUpperCaseType,
        .typeIdentifier: kUpperCaseSmallCapsSelector
     ]

    let lowerCaseFeature: [UIFontDescriptor.FeatureKey: Int] = [
        .featureIdentifier: kLowerCaseType,
        .typeIdentifier: kLowerCaseSmallCapsSelector
    ]

    let features = [upperCaseFeature, lowerCaseFeature]
    let additions = fontDescriptor.addingAttributes([.featureSettings: features])
    return UIFont(descriptor: additions, size: size)
}

}

Horatiu
  • 11
  • 2
-1

You can create a base UIViewController which hides the original navigationBar and add a new one by yourself.

self.navigationController.navigationBarHidden = YES;

UINavigationBar *navigationBar = [[UINavigationBar alloc] initWithFrame:frame];
UINavigationItem *naviItem = [[UINavigationItem alloc] init];
self.titleLabel = [UILabel new];
naviItem.titleView = self.titleLabel;
navigationBar.items = [NSArray arrayWithObjects:naviItem, nil];
[self.view addSubview:navigationBar];

Then you can control the setting of title for the titleLabel.

xi.lin
  • 3,326
  • 2
  • 31
  • 57