iOS Swift通过编程更改标签内的特定文本颜色
我的应用程序中有一些搜索选项,它将突出显示iOS Swift通过编程更改标签内的特定文本颜色,ios,swift3,attributes,nsattributedstring,nsmutableattributedstring,Ios,Swift3,Attributes,Nsattributedstring,Nsmutableattributedstring,我的应用程序中有一些搜索选项,它将突出显示ui搜索栏中的给定单词。给定的单词可能在标签中多次出现,我不需要突出显示所有这些单词。如何可能,我尝试了一些代码集,但它只会突出显示该单词的一个出现,以下是我的示例代码: var SearchAttributeText = "The" let range = (TextValue as NSString).range(of: SearchAttributeText) let attribute = NSMutableAttributedString.in
ui搜索栏中的给定单词。给定的单词可能在标签中多次出现,我不需要突出显示所有这些单词。如何可能,我尝试了一些代码集,但它只会突出显示该单词的一个出现,以下是我的示例代码:
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
需要同时支持上部
和下部
案例。Word该
可能出现多次,需要突出显示所有。您可以使用以下代码在字符串中搜索
//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))
}
}
下面的代码行通过增加NSRange
rangeString = NSMakeRange(colorRange.location + colorRange.length, contentString.length - (colorRange.location + colorRange.length))
请参阅本教程:@Bhadresh我已经引用了此博客。它们根据范围而不是给定字符更改颜色在的帮助下获取特定子字符串的所有范围并对其进行迭代。您可以使用NSRegularExpression
或range(of:)
上的for循环(注意range(of:)
具有“变体”使用选项(不区分大小写)来获取搜索文本的所有出现范围。