iosobjective-c

Adjust navigation bar title font size to fit text


Is it possible to adjust the font size of the navigation bar's title to fit the text?


Solution

  • You can create a UILabel and set it to UINavigationItem's titleView. See Apple doc: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UINavigationItem_Class/#//apple_ref/occ/instp/UINavigationItem/titleView

    For the created UILabel, you can set the adjustsFontSizeToFitWidth & minimumScaleFactor properties to let it fit the title. Doc: https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UILabel_Class/#//apple_ref/occ/instp/UILabel/adjustsFontSizeToFitWidth

    Some codes:

    - (void)setMyTitle:(NSString *)title
    {
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.navigationController.view.bounds.size.width - 100, 44)];
        titleLabel.text = title;
        titleLabel.font = [UIFont systemFontOfSize:16];
        titleLabel.textColor = ...
        ...
        self.navigationItem.titleView = titleLabel;
    }