简体   繁体   中英

How to use attributed string as navigation bar title in iOS 5.0?

Is there any way to use attributed label on navigation bar on iOS 5? I know it works in iOS 6+ but before that?
I want to use both bold and non bold font there.

You can use TTAttributedLabel to achieve this. Here is the code to do the trick. Suppose you want to set title to "Sample NavBarTitle" where the Sample should bold.

//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;

That's all.

Here is the code that helped me:

 // 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;

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