Taken from this answer here: https://stackoverflow.com/a/35770826/2617369
I used the extension to NSMutableAttributedString to loop through the array of items and managed to get them all colored. You just have to use the cell.textLabel?.attributedText
property of UILabel instead:
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).range(of: 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
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let allData = Singlton.Singleton.getAllData()
cell.detailTextLabel?.text = ""
var attributeText = NSMutableAttributedString(string: someData[indexPath.row])
for i in allData {
attributeText.attributeRangeFor(searchString: i, attributeValue: UIColor.yellow, atributeSearchType: .All)
}
cell.titleLabel?.attributedText = attributedText
return cell
}