0

我可以以某种方式为一个单词添加多种颜色NSAttributedString吗?换句话说,我想为特定单词添加颜色,颜色之间有或没有空格,例如<red>app</red><blue>ple</blue>. 这样苹果就有两种颜色。我附上了从这段代码中删除空格之前和之后发生的事情的照片:

这是我正在使用的代码。

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

  }
}

我也在这个线程中找到了代码是否可以更改 UITextView 和 UITextField 中单个单词的颜色

4

1 回答 1

1

我花了一天的时间来思考,但 \0 是诀窍。

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

于 2015-05-30T04:55:31.500 回答