gpt4 book ai didi

iOS Swift 以编程方式更改标签内的特定文本颜色

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:30:37 24 4
gpt4 key购买 nike

我的应用程序中有一些搜索选项,它会突出显示 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

需要支持 Upperlower 两种情况。单词可能会出现多次,需要全部高亮。

最佳答案

您可以使用以下代码在字符串中搜索

    //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))
}
}

下面的代码行通过增加 NSRangelocationlength 参数来更新范围

rangeString = NSMakeRange(colorRange.location + colorRange.length, contentString.length - (colorRange.location + colorRange.length))

关于iOS Swift 以编程方式更改标签内的特定文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47749098/

24 4 0