Created
June 8, 2023 20:47
-
-
Save alexpersian/82746a931fa31b1ba0b6526e5887e25a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func processHTML(_ string: String) -> NSAttributedString { | |
let stringData = string.data(using: .utf8)! | |
let attrString = try! NSMutableAttributedString( | |
data: stringData, | |
options: [.documentType: NSAttributedString.DocumentType.html], | |
documentAttributes: nil | |
) | |
var boldRanges: [NSRange] = [] | |
var italicRanges: [NSRange] = [] | |
var regularRanges: [NSRange] = [] | |
attrString.enumerateAttribute(.font, in: NSRange(0..<attrString.length), options: .longestEffectiveRangeNotRequired) { value, range, pointer in | |
guard let currentFont = value as? UIFont else { return } | |
if currentFont.fontDescriptor.symbolicTraits.contains(.traitBold) { | |
boldRanges.append(range) | |
} else if currentFont.fontDescriptor.symbolicTraits.contains(.traitItalic) { | |
italicRanges.append(range) | |
} else { | |
regularRanges.append(range) | |
} | |
} | |
boldRanges.forEach { range in | |
attrString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.systemRed, range: range) | |
} | |
italicRanges.forEach { range in | |
attrString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.systemBlue, range: range) | |
} | |
regularRanges.forEach { range in | |
attrString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.systemGreen, range: range) | |
} | |
return attrString | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment