【发布时间】:2015-08-11 20:47:42
【问题描述】:
我能否以某种方式为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
}
}
我也在这个线程Is it possible to change color of single word in UITextView and UITextField找到了代码
【问题讨论】:
-
我建议使用
NSRegularExpression而不是使用组件separatedByString:" "。否则,您必须使用[word rangeOfString:@"</number>"] != NSNotFound而不是hasSuffix:。
标签: ios swift cocoa-touch nsattributedstring text-styling