【问题标题】:How to apply both bold and italic font to an NSAttributedString?如何将粗体和斜体字体应用于 NSAttributedString?
【发布时间】:2014-09-24 17:32:47
【问题描述】:

我正在尝试将自己的 HTML 字符串解析为 NSAttributedString 以在 UITextView 中呈现。

所以,当字符串出现时:

<strong><em>这应该是粗体和斜体</strong></em>

我想为最终的 NSAttributedString 应用不同的粗体和斜体字体,这样如果用户在编辑过程中删除了粗体或斜体字体,剩余字体之一将保持不变。

这就是我不想像其他 SO 答案所建议的那样简单地应用像粗斜体这样的单一字体样式的主要原因。

【问题讨论】:

    标签: html ios nsattributedstring


    【解决方案1】:

    这是我查看不同来源后的答案:

    UIFontDescriptor *fontDescriptor = [UIFontDescriptor preferredFontDescriptorWithTextStyle:UIFontTextStyleBody];
    
    UIFontDescriptor *changedFontDescriptor;      
    NSDictionary *attributes;
    
    uint32_t existingTraitsWithNewTrait = [fontDescriptor symbolicTraits] | UIFontDescriptorTraitBold | UIFontDescriptorTraitItalic;
    changedFontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:existingTraitsWithNewTrait];
    
    UIFont *updatedFont = [UIFont fontWithDescriptor:changedFontDescriptor size:0.0];
    
    attributes = @{ NSFontAttributeName : updatedFont };
    
    attributedString = [[NSAttributedString alloc] initWithString:yourString attributes:attributes];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-02
      • 2011-07-18
      • 2014-07-07
      • 2012-12-10
      • 1970-01-01
      • 2015-01-11
      • 2016-08-10
      • 2019-07-20
      相关资源
      最近更新 更多