title: Changing specific text's color using NSMutableAttributedString in Swift
body: <p>The issue I am having is that I want to be able to change the textColor of certain text in a TextView. I am using a concatenated string, and just want the strings I am appending into the TextView's text. It appears that what I want to use is <code>NSMutableAttributedString</code>, but I am not finding any resources of how to use this in Swift. What I have so far is something like this:</p>
  
  <pre><code>let string = "A \(stringOne) with \(stringTwo)"
  var attributedString = NSMutableAttributedString(string: string)
  textView.attributedText = attributedString
  </code></pre>
  
  <p>From here I know I need to find the range of words that need to have their textColor changed and then add them to the attributed string. What I need to know is how to find the correct strings from the attributedString, and then change their textColor.</p>
  
  <p>Since I have too low of a rating I can't answer my own question, but here is the answer I found</p>
  
  <p>I found my own answer by translating from translating some code from </p>
  
  <p><a href="https://stackoverflow.com/questions/17486647/change-attributes-of-substrings-in-a-nsattributedstring">Change attributes of substrings in a NSAttributedString</a></p>
  
  <p>Here is the example of implementation in Swift:</p>
  
  <pre><code>let string = "A \(stringOne) and \(stringTwo)"
  var attributedString = NSMutableAttributedString(string:string)
  
  let stringOneRegex = NSRegularExpression(pattern: nameString, options: nil, error: nil)
  let stringOneMatches = stringOneRegex.matchesInString(longString, options: nil, range: NSMakeRange(0, attributedString.length))
  for stringOneMatch in stringOneMatches {
      let wordRange = stringOneMatch.rangeAtIndex(0)
      attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.nameColor(), range: wordRange)
  }
  
  textView.attributedText = attributedString
  </code></pre>
  
  <p>Since I am wanting to change the textColor of multiple Strings I will make a helper function to handle this, but this works for changing the textColor. </p>