如何将自定义字体应用于TTTAttributedLabel

时间:2014-03-21 08:57:06

标签: ios objective-c tttattributedlabel

我在我的项目中使用TTTAttributedLabel。我正在尝试为该标签应用自定义字体。

#define DEFAULT_FONT(s)     [UIFont fontWithName:MY_FONT_NAME size:s]

我使用以下代码设置字体:

@property(nonatomic, strong) TTTAttributedLabel *welcomeMessage;

NSString *welcomeMessageString = [[NSString stringWithFormat:@"%@",[self.dashboardViewModel getWelcomeMessage]] uppercaseString];
    [self.welcomeMessage setText:welcomeMessageString afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString){
        NSRange boldRange = [[mutableAttributedString string] rangeOfString:@"Welcome " options:NSCaseInsensitiveSearch];

        NSRange colorRange = NSMakeRange((boldRange.location + boldRange.length), (welcomeMessageString.length - boldRange.length));
        UIFont *systemBoldFont = DEFAULT_FONT(13);
        CTFontRef boldFont = CTFontCreateWithName((__bridge CFStringRef)systemBoldFont.fontName, systemBoldFont.pointSize, NULL);
        if (boldFont) {
            [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)RGB(134.0, 0, 0).CGColor range:colorRange];
            CFRelease(boldFont);

        }


        return mutableAttributedString;
    }];
    self.welcomeMessage.font = DEFAULT_FONT(13);

但在我的应用程序中,字体未应用。我需要"欢迎"黑色文本和文本的剩余部分为红色。但对于我的标签,我需要应用我的自定义字体。

2 个答案:

答案 0 :(得分:2)

试试这个,

 CTFontRef boldFont = CTFontCreateWithName((__bridge CFStringRef)systemBoldFont.fontName, systemBoldFont.pointSize, NULL);
    if (boldFont) {
        [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)boldFont range:nameRange];
        CFRelease(boldFont);

    }

答案 1 :(得分:0)

下面

if (boldFont) {
    [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)RGB(134.0, 0, 0).CGColor range:colorRange];
    CFRelease(boldFont);
}

您正在检查boldFont,然后添加颜色。这是对的吗?如果您需要使用kCTFontAttributeName键添加字体。