1
有什麼辦法可以在iOS 5的導航欄上使用歸屬標籤?我知道它適用於iOS 6+,但在此之前?
我想在那裏使用粗體字體和非粗體字體。如何在iOS 5.0中使用屬性字符串作爲導航欄標題?
有什麼辦法可以在iOS 5的導航欄上使用歸屬標籤?我知道它適用於iOS 6+,但在此之前?
我想在那裏使用粗體字體和非粗體字體。如何在iOS 5.0中使用屬性字符串作爲導航欄標題?
這裏是一個幫助過我的代碼:
// 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;
您可以使用TTAttributedLabel來實現此目的。這是執行這個技巧的代碼。假設您想將標題設置爲「樣本NavBarTitle」,其中樣本應該爲粗體。
//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;
這就是全部。
這看起來不錯,但NSFontAttributeName是iOS6的唯一枚舉。我可以用什麼來代替? – Dvole
@Dvole這個答案很好地回答你的問題,所以請接受它。如果您對其他iOS版本的「NSFontAttributeName」感興趣,請添加新問題,或編輯您當前的問題以包含該問題。 –
@FahriAzimov不是真的,它在iOS 5中崩潰。 – Dvole