我正在尝试在UINavigationBar中设置两行标签。当我执行以下操作时,它只显示一行(换行符之前的部分)。
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];
为了比较,以下显示两行。以下仅供比较。顶级版本是我需要的。
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];
帮助顶级版本正常运行的任何帮助?
答案 0 :(得分:2)
似乎在 label.sizeToFit()
之前调用self.navigationItem.titleView = label
会正确显示NSAttributedString标题。
(Swift,iOS8.1,XCode 6.1.1)
答案 1 :(得分:1)
简单的问题,简单的解决方案。即使您使用的是attributionText而不是text,仍然需要:
label.numberOfLines = 0;