I am trying to replace a substring with attributed String. Following is my code.
let searchText = self.searchBar.text!
let name = item.firstName ?? ""
let idNo = "Employee Id. \(item.employeeId ?? "NA")"
if let range = name.range(of: searchText, options: String.CompareOptions.caseInsensitive, range: nil, locale: nil)
{
let attributedSubString = NSAttributedString.init(string: name.substring(with: range), attributes: [NSFontAttributeName : UIFont.boldSystemFont(ofSize: 17)])
let normalNameString = NSMutableAttributedString.init(string: name)
normalNameString.mutableString.replacingCharacters(in: range, with: attributedSubString)
cell.name.attributedText = normalNameString
}
else
{
cell.name.text = name
}
I am getting compile time error:
"Cannot convert value of type 'Range' (aka 'Range') to expected argument type 'NSRange' (aka '_NSRange')".
What should I change here?
You can use NSString
and NSRange
, also you need to change this line normalNameString.mutableString.replacingCharacters(in: range, with: attributedSubString)
and use this one instead normalNameString.replaceCharacters(in: nsRange, with: attributedSubString)
because mutableString is NSMutableString, and replacingCharacters
expect String and not NSAttributtedString
Full code (Updated for Swift5)
let nsRange = NSString(string: name).range(of: searchText, options: String.CompareOptions.caseInsensitive)
if nsRange.location != NSNotFound
{
let attributedSubString = NSAttributedString.init(string: NSString(string: name).substring(with: nsRange), attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 17)])
let normalNameString = NSMutableAttributedString.init(string: name)
normalNameString.replaceCharacters(in: nsRange, with: attributedSubString)
cell.name.attributedText = normalNameString
}
else
{
cell.name.text = name
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With