Im applying a text attribute the string
"Updated - ".
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
I want this to apply to all occurences of the string
rather than just the one
Tried
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
}
This still only applies the attributed text to one occurrence of the string
Similar question Color all occurrences of string in swift
Update
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