Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UINavigationBar title label text

Is it possible to get the title text to shrink to fit in the UINavigationBar in iOS.

(for portrait iPhone app with no autolayout).

I'm setting the title bar dynamically but sometimes the text is too long and at the moment it just cuts it off with an ellipsis.

i.e. "This is the t..."

I'd like it to shrink the text instead.

like image 512
Fogmeister Avatar asked Jan 24 '13 15:01

Fogmeister


1 Answers

You can create your own title view to make it.

Something like this:

- (void)viewDidLoad
{
    [super viewDidLoad];

  //Do any additional setup after loading the view, typically from a nib.
     UILabel *titleLabelView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)]; //<<---- Actually will be auto-resized according to frame of navigation bar;
    [titleLabelView setBackgroundColor:[UIColor clearColor]];
    [titleLabelView setTextAlignment: NSTextAlignmentCenter];
    [titleLabelView setTextColor:[UIColor whiteColor]];
    [titleLabelView setFont:[UIFont systemFontOfSize: 27]]; //<<--- Greatest font size
    [titleLabelView setAdjustsFontSizeToFitWidth:YES]; //<<---- Allow shrink
     // [titleLabelView setAdjustsLetterSpacingToFitWidth:YES];  //<<-- Another option for iOS 6+
    titleLabelView.text = @"This is a Title";

    navigationBar.topItem.titleView = titleLabelView;

    //....
}

Hope this helps.

like image 76
Hail Zhang Avatar answered Nov 02 '22 21:11

Hail Zhang