2

I was wondering what is the best approach to make the UINavigationBar title auto shrink into minimum font size when it is too long?

Below are my example of the problem

Normal

enter image description here

Too Long (need to shrink the label)

enter image description here

And here is the codes I am using to do styling for UINavigationBar

[[UINavigationBar appearance] setBackgroundImage:[UIImage imageWithColor:[UIColor greenColor]]
                                   forBarMetrics:UIBarMetricsDefault];

[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

[[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName   : [UIColor whiteColor],
                                                       NSFontAttributeName              : [fontWithName:@"Helvetica-Bold" size:18.0]}];

[[UINavigationBar appearance] setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin];
Rajesh
  • 10,318
  • 16
  • 44
  • 64
Keith Yeoh
  • 731
  • 1
  • 7
  • 20

1 Answers1

3

The most common solution is to use a custom view for the title. But you can't do this using UIAppearance, you will need to do this on each UIViewController that you push, or make a category of the UINavigationBar, and add this logic every time the title text is changed (Not sure if this will work or if it's a good idea, though) or create a new adhoc method.

For example (Put this in the viewDidLoad of your UIViewController):

UILabel* titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0, 200, 40)];
titleLabel.text = @"Your very long title";
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textColor = [UIColor whiteColor];
titleLabel.adjustsFontSizeToFitWidth = YES; // As alternative you can also make it multi-line. 
titleLabel.minimumScaleFactor = 0.5;     
self.navigationItem.titleView = titleLabel;
JP Illanes
  • 3,665
  • 39
  • 56