Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributedString in UINavigationBar not showing both lines of text

I am trying to set a two line label in my UINavigationBar. When I do the following, it only shows one line (the part before the line break).

NSString *title = @"First line of title is bigger\nSecond line of title is smaller";
NSDictionary *attribute1 = @{NSForegroundColorAttributeName: [UIColor colorWithRed:148/255.0f green:147/255.0f blue:147/255.0f alpha:1],
                             NSFontAttributeName: [UIFont boldSystemFontOfSize: 14.0f]};
NSDictionary *attribute2 = @{NSForegroundColorAttributeName: [UIColor colorWithRed:148/255.0f green:147/255.0f blue:147/255.0f alpha:1],
                             NSFontAttributeName: [UIFont boldSystemFontOfSize: 10.0f]};
const NSRange line1Range = {0, 29};
const NSRange line2Range = {31, 30};

NSMutableAttributedString *attributedText =[[NSMutableAttributedString alloc] initWithString:title];
[attributedText setAttributes: attribute1 range:line1Range];
[attributedText setAttributes: attribute2 range:line2Range];

UILabel *label = [[UILabel alloc] init];
label.attributedText=attributedText;
self.navigationItem.titleView = label;
[self.navigationItem.titleView sizeToFit];

For comparison, the following shows both line. The following is for comparison only. The top version is what I need.

UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor clearColor];
label.numberOfLines = 2;
label.font = [UIFont boldSystemFontOfSize: 14.0f];
label.textColor = [UIColor colorWithRed:148/255.0f green:147/255.0f blue:147/255.0f alpha:1];
label.text = @"First line of title is bigger\nSecond line of title is smaller";

self.navigationItem.titleView = label;
[self.navigationItem.titleView sizeToFit];

Any help getting the top version to work correctly?

like image 332
learner Avatar asked Oct 21 '22 03:10

learner


1 Answers

It appears that calling label.sizeToFit() before self.navigationItem.titleView = label displays the NSAttributedString title correctly.

(Swift, iOS8.1, XCode 6.1.1)

like image 114
dadsoup Avatar answered Oct 23 '22 04:10

dadsoup