【发布时间】:2015-07-28 16:57:23
【问题描述】:
我正在应用string“更新-”的文本属性。
var attributedText: NSMutableAttributedString = NSMutableAttributedString(string: textView.text)
let rangeOfString = (textView.text as NSString).rangeOfString("Updated - ")
attributedText.addAttributes([NSFontAttributeName: UIFont.italicSystemFontOfSize(8.0)],range: rangeOfString)
textView.attributedText = attributedText
我希望这适用于string 的所有次出现,而不仅仅是一个
试过了
var attributedText: NSMutableAttributedString = NSMutableAttributedString(string: textView.text)
let stringRange = (textView.text as NSString).rangeOfString("Updated - ")
if (stringRange.location != NSNotFound) {
attributedText.addAttributes([NSFontAttributeName: UIFont.italicSystemFontOfSize(8.0)],range: stringRange)
textView.attributedText = attributedText
}
这仍然只将属性文本应用于string 的一次出现
类似问题Color all occurrences of string in swift
更新
var attributedText: NSMutableAttributedString = NSMutableAttributedString(string: textView.text)
var inputLength = count(attributedText.string)
let stringRange = "Updated - "
var searchLength = count(stringRange)
var range = NSRange(location: 0, length: attributedText.length)
while (range.location != NSNotFound) {
range = (attributedText.string as NSString).rangeOfString("Updated - ", options: nil, range: range)
if (range.location != NSNotFound) {
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIFont.italicSystemFontOfSize(8.0), range: NSRange(location: range.location, length: searchLength))
range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
}
}
textView.attributedText = attributedText
【问题讨论】: