有没有办法在iOS 5的导航栏上使用属性标签?我知道它适用于iOS 6+但在此之前?
我想在那里使用粗体和非粗体字体。
答案 0 :(得分:4)
您可以使用TTAttributedLabel来实现此目的。这是诀窍的代码。假设您要将标题设置为“Sample NavBarTitle”,其中Sample应为粗体。
//In your code there may be several ranges, corresponding to how many attributes you want to have
NSRange range = NSMakeRange(0, 6);
//Initialize NSMutableAttributedString
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"Sample NavBarTitle"];
//Set the attribute to make "Sample" bold
[string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia-Bold" size:15] range:range];
//Initialize TTAttributedLabel with rect
TTTAttributedLabel * label = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(0, 0, 20, 150)];
//Set the attributedText property of TTAttributedLabel
label.attributedText = string;
//Set navigationItem.titleView to the label view we've created
self.navigationItem.titleView = label;
就是这样。
答案 1 :(得分:2)
这是帮助我的代码:
// Total string
NSString *tempString = [NSString stringWithFormat:@"%@, %@ %@ %@ %@", gameName, stringConnector, self.bet.gameInfo.draw.drawNumber, stringConnector2, [dateFormatter stringFromDate:self.bet.gameInfo.draw.date]];
NSRange range = [tempString rangeOfString:gameName];
NSMutableAttributedString * string2 = [[NSMutableAttributedString alloc] initWithString:tempString];
// font for all string
UIFont *regularFont = [UIFont fontWithName:BEAU_PRO_LIGHT_FONT_NAME size:21];
CTFontRef font_2 = CTFontCreateWithName((__bridge CFStringRef)regularFont.fontName, regularFont.pointSize, NULL);
[string2 addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font_2 range:[tempString rangeOfString:tempString]];
// bold font
UIFont *boldFont = [UIFont fontWithName:BEAU_PRO_SEMIBOLD_FONT_NAME size:21];
CTFontRef font_1 = CTFontCreateWithName((__bridge CFStringRef)boldFont.fontName, boldFont.pointSize, NULL);
[string2 addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font_1 range:range];
TTTAttributedLabel * label = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(0, 0, 600, 20)];
label.attributedText = string2;
[label sizeToFit];
self.navigationItem.titleView = label;