# Usage
// Sample private lazy var titleLabel: UILabel = { let label = UILabel() label.textColor = UIColor.lightGray label.font = UIFont.systemFont(ofSize: 16) label.numberOfLines = 0 return label }() let red = "red" let blue = "blue" let green = "green" let stringValue = "\(red)\n\(blue)\n&\n\(green)" let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue) attributedString.setColor(color: UIColor.red, forText: red) // or use direct value for text "red" attributedString.setColor(color: UIColor.green, forText: green) // or use direct value for text "blue" attributedString.setColor(color: UIColor.blue, forText: blue) // or use direct value for text "green" attributedString.setFont(font: UIFont.systemFont(ofSize: 24), forText: green) label.attributedText = attributedString
# Extension Sample
// Extension. extension NSMutableAttributedString { func setColor(color: UIColor, forText stringValue: String) { let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive) self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range) } func setFont(font: UIFont, forText stringValue: String) { let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive) self.addAttribute(NSAttributedString.Key.font, value: font, range: range) } }