【问题标题】:iOS Swift Change Particular Text Color Inside Label ProgramaticallyiOS Swift以编程方式更改标签内的特定文本颜色
【发布时间】:2018-05-24 18:00:08
【问题描述】:

我的应用中有一些搜索选项,它将突出显示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 情况。字The可能出现多次,需要全部高亮。

【问题讨论】:

  • @Bhadresh 我已经提到了这个博客,他们根据范围而不是给定字符改变颜色
  • this question的帮助下获取特定子字符串的所有范围并遍历它们。
  • 您可以在range(of:) 上使用NSRegularExpression 或for 循环(注意range(of:) 具有“变体”以及不区分大小写等选项)来获取搜索文本出现的所有范围.

标签: ios swift3 attributes nsattributedstring nsmutableattributedstring


【解决方案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))
        }
    }

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

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

【讨论】:

    猜你喜欢
    • 2022-08-22
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多