zucchero sintassi per la risposta di Kevin sopra.
Chiamato come:
attrStr.attributeRangeFor(searchString, attributeValue: UIColor.yellowColor(), atributeSearchType: .All)
Swift 2.0:
import UIKit
extension NSMutableAttributedString {
enum AtributeSearchType {
case First, All, Last
}
func attributeRangeFor(searchString: String, attributeValue: AnyObject, atributeSearchType: AtributeSearchType) {
let inputLength = self.string.characters.count
let searchLength = searchString.characters.count
var range = NSRange(location: 0, length: self.length)
var rangeCollection = [NSRange]()
while (range.location != NSNotFound) {
range = (self.string as NSString).rangeOfString(searchString, options: [], range: range)
if (range.location != NSNotFound) {
switch atributeSearchType {
case .First:
self.addAttribute(NSForegroundColorAttributeName, value: attributeValue, range: NSRange(location: range.location, length: searchLength))
return
case .All:
self.addAttribute(NSForegroundColorAttributeName, value: attributeValue, range: NSRange(location: range.location, length: searchLength))
break
case .Last:
rangeCollection.append(range)
break
}
range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
}
}
switch atributeSearchType {
case .Last:
let indexOfLast = rangeCollection.count - 1
self.addAttribute(NSForegroundColorAttributeName, value: attributeValue, range: rangeCollection[indexOfLast])
break
default:
break
}
}
}
tua soluzione è in Objective-C:/ – jjx
ha scritto nel Swift dal http://stackoverflow.com/questions/8533691/how-to-get-all-nsrange-of-a-particular-character- in-a-nsstring? lq = 1 – Kevin