Skip to content

Instantly share code, notes, and snippets.

@michaelevensen
Last active November 28, 2016 19:54
Show Gist options
  • Save michaelevensen/e9cb85d20e9cd9e05cc6f250c5f121a0 to your computer and use it in GitHub Desktop.
Save michaelevensen/e9cb85d20e9cd9e05cc6f250c5f121a0 to your computer and use it in GitHub Desktop.
Color parts of words in attributedString. Note: Also respects any previous attributes set in Storyboard (colored words or lineHeightMultiple etc.). Also a simple function which just makes a new NSMutableString with the defined text value while keeping all existing attributes.
extension NSAttributedString {
// MARK: - Makes a copy of the existing attributes for NSAttributedString and sets color for specific string(s)
func makeStringWithColor(forString stringArray: [String], withColor color: UIColor) -> NSMutableAttributedString {
// Existing attributes
let attributedString = NSMutableAttributedString(attributedString: self)
// Iterate through strings
for specifiedString in stringArray {
// Whole range (for regex)
let range = NSMakeRange(0, self.string.characters.count)
// Find several occurences
do {
let regex = try NSRegularExpression(pattern: specifiedString, options: .caseInsensitive)
// Enumerate matches
regex.enumerateMatches(in: self.string, options: .reportCompletion, range: range, using: { (result, _, _) in
// Substring range
if let subStringRange = result?.rangeAt(0) {
attributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: subStringRange)
}
})
}
catch {
print(error)
}
}
return attributedString
}
// MARK: - Makes a copy of existing attributes for NSAttributedString and returns a new NSMutableString with a new text / string.
func makeStringWith(text newString: String) -> NSMutableAttributedString {
// Keep existing attributes
let attributedString = NSMutableAttributedString(attributedString: self)
// Update string, keep attributes
attributedString.mutableString.setString(newString)
return attributedString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment