简体   繁体   English

NSAttributedString 改变字体大小

[英]NSAttributedString change font size

I have an NSAttributedString which may have multiple subranges with different font styles and other attributes.我有一个 NSAttributedString ,它可能有多个具有不同字体样式和其他属性的子范围。 How do I modify the size of font for the whole attributed string?如何修改整个属性字符串的字体大小? Setting a font size of 20 should set pointSize of all fonts in the string to 20.将字体大小设置为 20 应该将字符串中所有字体的 pointSize 设置为 20。

With these extensions you will be able to easily change font size of the NSAttributedString in all of the subranges leaving other font parameters the same.使用这些扩展,您将能够轻松更改所有子范围中NSAttributedString的字体大小,而其他字体参数保持不变。

Usage用法

let label: UILabel = ...
let string: NSAttributedString = ...

label.attributedText = string.mutable.setFontSize(20)

Extensions扩展

extension NSMutableAttributedString {
    func setFontSize(_ fontSize: CGFloat) {
        beginEditing()
        enumerateAttribute(.font, in: completeRange) { value, range, _ in
            guard
                let fontFromAttribute = value as? UIFont,
                let descriptor = fontFromAttribute.fontDescriptor
                    .withSymbolicTraits(fontFromAttribute.fontDescriptor.symbolicTraits)
            else { return }
            let font = UIFont(descriptor: descriptor, size: fontSize)
            addAttribute(.font, value: font, range: range)
        }
        endEditing()
    }
}
extension NSAttributedString {
    var mutable: NSMutableAttributedString {
        NSMutableAttributedString(attributedString: self)
    }

    var completeRange: NSRange { 
        NSRange(location: 0, length: self.length) 
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM