Skip to content

Instantly share code, notes, and snippets.

@Jegge
Created February 13, 2022 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jegge/3cf8edede7b86976e901e4a2beafe924 to your computer and use it in GitHub Desktop.
Save Jegge/3cf8edede7b86976e901e4a2beafe924 to your computer and use it in GitHub Desktop.
Some helpers to manipulate the attributes of a NSAttributedString
extension NSAttributedString {
convenience init? (html: String) {
let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]
guard
let data = html.data(using: .utf16, allowLossyConversion: true),
let text = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil)
else {
return nil
}
self.init(attributedString: text)
}
/// Returns a new `NSAttributedString` with a changed font face, but the same traits (bold, italic) and size
func setting (font: UIFont) -> NSAttributedString {
let result = NSMutableAttributedString(attributedString: self)
self.enumerateAttribute(.font, in: NSRange(location: 0, length: self.length), options: .longestEffectiveRangeNotRequired) { attribute, range, _ in
if let descriptor = (attribute as? UIFont)?.fontDescriptor {
let newFont = UIFont(descriptor: font.fontDescriptor.withSymbolicTraits(descriptor.symbolicTraits)!, size: 0)
result.addAttribute(.font, value: newFont, range: range)
}
}
return result
}
/// Returns a new `NSAttributedString` with a changed foreground and background color.
func setting (textColor: UIColor, backgroundColor: UIColor) -> NSAttributedString {
let result = NSMutableAttributedString(attributedString: self)
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: textColor,
.backgroundColor: backgroundColor
]
result.addAttributes(attributes, range: NSRange(location: 0, length: result.length))
return result
}
/// Returns a new `NSAttributedString`, but updates all paragraph styles to use a given hyphenation factor.
func setting (hyphenationFactor: Float) -> NSAttributedString {
let result = NSMutableAttributedString(attributedString: self)
self.enumerateAttribute(.paragraphStyle, in: NSRange(location: 0, length: self.length), options: .longestEffectiveRangeNotRequired) { attribute, range, _ in
if let paragraph = (attribute as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle {
paragraph.hyphenationFactor = hyphenationFactor
result.addAttribute(.paragraphStyle, value: paragraph, range: range)
}
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment