【问题标题】:How to apply custom font to TTTAttributedLabel如何将自定义字体应用于 TTTAttributedLabel
【发布时间】:2014-03-21 08:57:05
【问题描述】:

我在我的项目中使用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);

但在我的应用程序中,字体没有被应用。我需要黑色的“欢迎”文本,文本的其余部分为红色。但对于我的标签,我需要应用我的自定义字体。

【问题讨论】:

  • 你是否在 info.plist 文件中添加了字体名称?
  • 是的,我添加了@SujithPt

标签: ios objective-c tttattributedlabel


【解决方案1】:

试试这个,

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

    }

【讨论】:

  • 我需要为特定范围添加字体颜色。但我希望字体应用于标签
  • @Vinodh 在您的代码中颜色是否有效或字体和颜色都无效?
  • 上面的代码可以设置字体,也可以用这个添加颜色代码
【解决方案2】:

这里

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-26
    • 2013-08-11
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    相关资源
    最近更新 更多