【问题标题】:How to selectively italicize text when using +[UIFont preferredFontForTextStyle:xxx]?使用 +[UIFont preferredFontForTextStyle:xxx] 时如何选择性地斜体化文本?
【发布时间】:2017-02-27 01:56:43
【问题描述】:

我像这样创建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;

但由于我从未要求过特定的字体,所以我不确定该怎么做。

【问题讨论】:

标签: ios nsattributedstring


【解决方案1】:
// 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 };

【讨论】:

    【解决方案2】:

    使用 RobertJoseph 的答案制作 Swift 3 扩展。

    extension UIFont {
    
        class func preferredItalicFont(forTextStyle style: UIFontTextStyle) -> UIFont? {
            return UIFont.preferredFont(forTextStyle: style).italicisedVariant
        }
    
        var italicisedVariant: UIFont? {
            guard let italicDescriptor = fontDescriptor.withSymbolicTraits(.traitItalic) else { return nil }
            return UIFont(descriptor: italicDescriptor, size: pointSize)
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 2013-02-24
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      相关资源
      最近更新 更多