【问题标题】:Two different colors in one word in an NSAttributedStringNSAttributedString 中的一个单词有两种不同的颜色
【发布时间】: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:@"&lt;/number&gt;"] != NSNotFound 而不是hasSuffix:

标签: ios swift cocoa-touch nsattributedstring text-styling


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 2014-04-03
    • 2013-09-17
    • 2015-08-05
    相关资源
    最近更新 更多