dnaatwork.com
dnaatwork.com

Reputation: 372

Two different colors in one word in an NSAttributedString

Can I somehow add multiple colors to a single word in an NSAttributedString? In other words, I want to add colors to specific words, with or without a space between colors, such as <red>app</red><blue>ple</blue>. That way apple has two colors. I have attached photos of what happens before and after removing the space from this code:

This is the code that I am using.

import UIKit
import Foundation
class ViewController: UIViewController {
    @IBOutlet var textView: UITextField!
    @IBOutlet var textBox: UITextField!
 override func viewDidLoad() {
     super.viewDidLoad()
     // Do any additional setup after loading the view, typically from a nib.
     self.textView.attributedText = self.a("the only <number>number</number>one which has no space")
   }
  override func didReceiveMemoryWarning() {
     super.didReceiveMemoryWarning()
       // Dispose of any resources that can be recreated.
    }
 func a(text:String) -> NSMutableAttributedString{
     var string:NSMutableAttributedString = NSMutableAttributedString(string: text)
        var words:[NSString] = text.componentsSeparatedByString(" ")
      for (var word:NSString) in words {
         if (word.hasPrefix("<number>") && word.hasSuffix("</number>")) {
                var range: NSRange = (string.string as NSString).rangeOfString(word as String)
                string.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
              word = word.stringByReplacingOccurrencesOfString("<number>", withString: "")
                word = word.stringByReplacingOccurrencesOfString("</number>", withString: "")
              string.replaceCharactersInRange(range, withString: word as String)
            }
     }
     return string

  }
}

Also I found the code in this thread Is it possible to change color of single word in UITextView and UITextField

Upvotes: 0

Views: 839

Answers (1)

dnaatwork.com
dnaatwork.com

Reputation: 372

It took me a day to ponder, but \0 was the trick.

NSMutableAttributedString(string: text) var words:[NSString] = text.componentsSeparatedByString("\0")

Upvotes: 1

Related Questions