Home > Back-end >  NSAttributedString change font size
NSAttributedString change font size

Time:06-17

I have an NSAttributedString which may have multiple subranges with different font styles and other attributes. 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.

CodePudding user response:

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.

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) 
    }
}
  • Related