NSAttributedString, change the font overall BUT keep all other attributes?

前端 未结 6 873
长情又很酷
长情又很酷 2020-11-28 08:24

Say I have an NSMutableAttributedString .

The string has a varied mix of formatting throughout:

Here is an example:

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 09:12

    Here is a much simpler implementation that keeps all attributes in place, including all font attributes except it allows you to change the font face.

    Note that this only makes use of the font face (name) of the passed in font. The size is kept from the existing font. If you want to also change all of the existing font sizes to the new size, change f.pointSize to font.pointSize.

    extension NSMutableAttributedString {
        func replaceFont(with font: UIFont) {
            beginEditing()
            self.enumerateAttribute(.font, in: NSRange(location: 0, length: self.length)) { (value, range, stop) in
                if let f = value as? UIFont {
                    let ufd = f.fontDescriptor.withFamily(font.familyName).withSymbolicTraits(f.fontDescriptor.symbolicTraits)!
                    let newFont = UIFont(descriptor: ufd, size: f.pointSize)
                    removeAttribute(.font, range: range)
                    addAttribute(.font, value: newFont, range: range)
                }
            }
            endEditing()
        }
    }
    

    And to use it:

    let someMutableAttributedString = ... // some attributed string with some font face you want to change
    someMutableAttributedString.replaceFont(with: UIFont.systemFont(ofSize: 12))
    

提交回复
热议问题