ios - 使用 +[UIFont preferredFontForTextStyle :xxx]? 时如何有选择地将文本设为斜体

标签 ios nsattributedstring

我像这样创建一个 NSMutableAttributedString:

UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
NSDictionary *attributes = @{ NSFontAttributeName: font };
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str attributes:attributes];

现在我想斜体化 attrStr 的特定范围,例如:

- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;

但由于我从未要求过特定字体,所以我不确定该如何处理。

最佳答案

// Create the normal body style font    
UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];

// Get the font's descriptor and add the italics trait
UIFontDescriptor *fontDesc = [font fontDescriptor];
fontDesc = [fontDesc fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitItalic];

// Create the italicized font from the descriptor
UIFont *italicsFont = [UIFont fontWithDescriptor:fontDesc size:font.pointSize];

// Create the attributes dictionary that we'll use to italicize parts of our NSMutableAttributedString
NSDictionary *italicsAttributes = @{ NSFontAttributeName: italicsFont };

关于ios - 使用 +[UIFont preferredFontForTextStyle :xxx]? 时如何有选择地将文本设为斜体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25426189/

相关文章:

ios - 在 iOS 9 中点击 UITextView 中的 NSLinkAttributeName 链接不起作用

ios - 如果发生溢出,如何为 UITextView 设置最大高度和固定宽度并强制省略而不是滚动?

iphone - iOS 捕捉视频

swift - 在字符串中添加和格式化前导零

ios - 多行文本的选定 UITextRange 调整的 CGRect?

ios - 为 NSAttributedstring 的不同部分应用不同的属性

ios - 裁剪图像 swift ios

ios - 如何在 Swift 2.0 中获取以分钟为单位的时差

ios - 减慢 UIDynamicAnimator 的动画

objective-c - 使用中世纪(小写,无衬里)数字