OGeek|极客世界-中国程序员成长平台

标题: ios - 使用自定义字体时,UITextView 属性文本不起作用 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 11:17
标题: ios - 使用自定义字体时,UITextView 属性文本不起作用

我正在使用 UITextView 并通过代码设置其字体和属性文本。

案例 1: 自定义字体 - 是属性文本 - 否

enter image description here

textView 文本以自定义字体显示。

我想要带有自定义字体的属性文本,即 Message : 在这种情况下应该加粗。

案例 2: 自定义字体 - 是属性文本 - 是

enter image description here

只有属性文本(粗体文本)以自定义字体显示。

我的代码是:

- (void)loadTextView
{
    _textView.text=NSLocalizedString(@"more_info_text",nil);
    _textView.font=[UIFont fontWithName"BurbankSmall-Medium" size:16];

    NSRange rangeBold  = [_textView.text rangeOfString"Examples of invalid characters:"];
    NSRange rangeBold2 = [_textView.text rangeOfString"Restricted text:"];
    NSRange rangeBold3 = [_textView.text rangeOfString"Message :"];

    UIFont *fontText = [self boldFontWithFont:_textView.font];
    NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil];

    NSMutableAttributedString *mutAttrTextViewString = [[NSMutableAttributedString alloc] initWithString:_textView.text];
    [mutAttrTextViewString setAttributes:dictBoldText range:rangeBold];
    [mutAttrTextViewString setAttributes:dictBoldText range:rangeBold2];
    [mutAttrTextViewString setAttributes:dictBoldText range:rangeBold3];

    [_textView setAttributedText:mutAttrTextViewString];

    _textView.editable=NO;
    _textView.selectable=NO;
}

- (UIFont *)boldFontWithFontUIFont *)font
{
    UIFontDescriptor * fontD = [font.fontDescriptor
                                fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold];
    return [UIFont fontWithDescriptor:fontD size:16];
}

当我评论 setAttributedText:mutAttrTextViewString 行时,evrything 会以自定义字体显示。当我取消注释时,只有属性文本以自定义字体显示,其余以默认字体显示。

为什么会这样?如果这不可能,我正在考虑将 html 内容作为属性文本包含在内,但我想在最坏的情况下将其视为一个选项。



Best Answer-推荐答案


有一个相关问题here .
主要问题是 UITextViewfont (UIFont) 属性将应用于其 text (NSString) 属性(也称为“纯文本”)而不是 attributedText (NSAttributedString)。

所以你必须自己为你的 NSAttributedString 应用“正常”字体效果。

所以只需替换:

NSMutableAttributedString *mutAttrTextViewString = [[NSMutableAttributedString alloc] initWithString:_textView.text];

与:

NSMutableAttributedString *mutAttrTextViewString = [[NSMutableAttributedString alloc] initWithString:_textView.text attributes{NSFontAttributeName:[UIFont fontWithName"BurbankSmall-Medium" size:16]}];

关于ios - 使用自定义字体时,UITextView 属性文本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37120535/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4