简体   繁体   中英

Dynamically adjust font size in UINavigationBar

What I want to do is this :

I've a navigation bar using an image covering the whole bar and looking like this:

在此处输入图片说明

Now I want to put the title on the black part of the bar and so it doesn't impinge on the icon. This title may be very short or very long. So I tried this:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
label.backgroundColor = [UIColor blackColor];
label.numberOfLines = 2;
label.minimumFontSize = 8.;
label.adjustsFontSizeToFitWidth = YES;
label.font = [UIFont boldSystemFontOfSize:16.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = UITextAlignmentCenter;
label.textColor =[UIColor whiteColor];
label.text = name;
self.navigationItem.titleView = label;

But this is not working because the label's width grows if needed upon the label and exceeds 200px.

What should I do then? Thanks for your help.

PS : the camera icon is not a button.

Your code works fine in iOS 7.0

Since you are using UITextAlignmentCenter (instead of NSTextAlignmentCenter), and also using minimumFontSize, I am assuming you are running on an earlier version of iOS, since these were both deprecated in iOS 6.0

The main problem is that adjustsFontSizeToFitWidth only works in iOS6 and earlier if the numberOfLines is set to 1

As you can see in the apple developer documentation

https://developer.apple.com/library/ios/documentation/uikit/reference/UILabel_Class/Reference/UILabel.html#//apple_ref/occ/instp/UILabel/adjustsFontSizeToFitWidth

If you necessarily want two lines and also want the font size to adjust... you could maybe just use the length property of your name string, which would tell you how many characters are in the string, and you could then set the font size according to the length of the string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM