如何将粗体和斜体字体应用于NSAttributedString? [英] How to apply both bold and italic font to an NSAttributedString?

查看:92
本文介绍了如何将粗体和斜体字体应用于NSAttributedString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



所以,当字符串出现时:


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


$ p

我想要应用一个明显的粗体斜体字体和最终的NSAttributedString,所以如果用户在编辑过程中删除粗体或斜体字体,其余的字体将保持不变。



这就是为什么我不只是想像粗体 - 斜体一样应用单一字体样式的主要原因,正如其他SO答案所建议的那样。 解决方案这是我查看不同来源后的答案:

  UIFontDescriptor * fontDescriptor = [UIFontDescriptor preferredFontDescriptorWithTextStyle:UIFontTextStyleBody]; 

UIFontDescriptor * changedFontDescriptor;
NSDictionary *属性;

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];


I'm trying to parse my own HTML string into an NSAttributedString for rendering in a UITextView.

So, for when the string appears as such:

<strong><em>This should be both bold and italic</strong></em>

I want to apply a distinct bold and italic font to the eventual NSAttributedString, so that if the user ever removes either the bold or italic font from it during editing, one of the remaining fonts will stay intact.

This is the main reason why I don't simply want to apply a single font style like bold-italic, as other SO answers have suggested.

解决方案

Here is my answer after looking through different sources:

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];

这篇关于如何将粗体和斜体字体应用于NSAttributedString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆