为搜索词Swift 2

时间:2016-06-26 17:43:48

标签: ios swift swift2

我有一个循环,它通过一个字符串数组来查找字符串。我有一个变量“searchText”,我想用字符串“aText”中的红色突出显示。

    for var i = 0; i < aArray?.count; i += 1 {

        if aArray![i].rangeOfString(searchText) != nil && counter != 100{
            counter += 1  
            var aText = aArray![i]
            var bText = "Example text B"
            var results = "\(aText) \n \(bText)"

            resultText.text = (resultText.text + "\n" + results)   

    }

}

我使用过NSMutableAttributedString,但没有用。我对Swift很新,并尝试了很多方法。其中一个主要问题是因为它处于循环中而且我多次更新UITextView

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

//inside Loop

if aArray![i] == "searchText" {
     var searchString:NSString = "The Result is "+aArray![i]
     let count = aArray![i].length
     var myMutableString = NSMutableAttributedString(string: searchString.description)  
     myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(), range:NSRange(location: 0, length: 14))// i calculated manually .
     myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range:NSRange(location: 14, length: searchString.length))

}