Changing specific text's color using NSMutableAttributedString in Swift Changing specific text's color using NSMutableAttributedString in Swift ios ios

Changing specific text's color using NSMutableAttributedString in Swift


let mainString = "Hello World"let stringToColor = "World"

SWIFT 5

let range = (mainString as NSString).range(of: stringToColor)let mutableAttributedString = NSMutableAttributedString.init(string: mainString)mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))textField.attributedText = mutableAttributedString

SWIFT 4.2

let range = (mainString as NSString).range(of: stringToColor)    let mutableAttributedString = NSMutableAttributedString.init(string: mainString)mutableAttributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)         textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))textField.attributedText = mutableAttributedString


I see you have answered the question somewhat, but to provide a slightly more concise way without using regex to answer to the title question:

To change the colour of a length of text you need to know the start and end index of the coloured-to-be characters in the string e.g.

var main_string = "Hello World"var string_to_color = "World"var range = (main_string as NSString).rangeOfString(string_to_color)

Then you convert to attributed string and use 'add attribute' with NSForegroundColorAttributeName:

var attributedString = NSMutableAttributedString(string:main_string)attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)

A list of further standard attributes you can set can be found in Apple's documentation


Swift 2.1 Update:

 let text = "We tried to make this app as most intuitive as possible for you. If you have any questions don't hesitate to ask us. For a detailed manual just click here." let linkTextWithColor = "click here" let range = (text as NSString).rangeOfString(linkTextWithColor) let attributedString = NSMutableAttributedString(string:text) attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range) self.helpText.attributedText = attributedString

self.helpText is a UILabel outlet.