我的应用中有一些搜索选项,会在keytool
中突出显示给定的字词。鉴于单词可能在标签中出现多次,我需要突出显示所有这些单词。怎么可能,我尝试了一些代码但它只会突出显示该单词的一次,这是我的示例代码:
UISearchBar
需要同时支持var SearchAttributeText = "The"
let range = (TextValue as NSString).range(of: SearchAttributeText)
let attribute = NSMutableAttributedString.init(string: TextValue)
attribute.addAttribute(NSForegroundColorAttributeName, value: UIColor.red , range: range)
self.label.attributedText = attribute
和Upper
个案例。单词lower
可能会多次出现,需要突出显示所有内容。
答案 0 :(得分:1)
您可以使用以下代码搜索字符串
//Text need to be searched
let SearchAttributeText = "the"
//Store label text in variable as NSString
let contentString = lblContent.text! as NSString
//Create range of label text
var rangeString = NSMakeRange(0, contentString.length)
//Convert label text into attributed string
let attribute = NSMutableAttributedString.init(string: contentString as String)
while (rangeString.length != NSNotFound && rangeString.location != NSNotFound) {
//Get the range of search text
let colorRange = (lblContent.text?.lowercased() as! NSString).range(of: SearchAttributeText, options: NSString.CompareOptions(rawValue: 0), range: rangeString)
if (colorRange.location == NSNotFound) {
//If location is not present in the string the loop will break
break
} else {
//This line of code colour the searched text
attribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red , range: colorRange)
lblContent.attributedText = attribute
//This line of code increment the rangeString variable
rangeString = NSMakeRange(colorRange.location + colorRange.length, contentString.length - (colorRange.location + colorRange.length))
}
}
以下代码行通过递增location
length
和NSRange
参数来更新范围
rangeString = NSMakeRange(colorRange.location + colorRange.length, contentString.length - (colorRange.location + colorRange.length))