UITextView使用swift突出显示所有匹配项

我想通过搜索突出显示所有匹配单词.我写了代码,但我不能使用循环.当我搜索一个单词时,我的应用程序会找到单词并突出显示一个单词.这是我的代码
var count = 0
let attributedText = NSMutableAttributedString(attributedString: txtMetin2.attributedText)
let text2 = txtarama.text as Nsstring
let text = txtMetin2.text as Nsstring
var range:NSRange
var checker:Nsstring = ""

for(var i=0 ; i<text.length - text2.length-1 ; i++)
{        
    range = NSMakeRange(i,text2.length)
    checker = text.substringWithRange(range)
    if(text2 == checker)
    {
        count++    
        let highlightedRange = text.rangeOfString("\(text2)")
        attributedText.addAttribute(NSBackgroundColorAttributeName,value: UIColor.blueColor(),range: highlightedRange)
        let textAttachment = NSTextAttachment()
        let textAttachmentString = NSAttributedString(attachment: textAttachment)
        attributedText.appendAttributedString(textAttachmentString)
        txtMetin2.attributedText = attributedText                               
    }
}
println("\(count)")

我很快就是新人.抱歉编码不好.我的代码找到匹配数,但我怎么能突出所有匹配谢谢你

基于强制性 NSRegularExpression解决方案.
let searchString = "this"
let baseString = "This is some string that contains the word \"this\" more than once. This substring has multiple cases. ThisthisThIs."

let attributed = NSMutableAttributedString(string: baseString)

var error: NSError?
let regex = NSRegularExpression(pattern: searchString,options: .CaseInsensitive,error: &error)

if let regexError = error {
    println("Oh no! \(regexError)")
} else {
    for match in regex?.matchesInString(baseString,options: NSMatchingOptions.allZeros,range: NSRange(location: 0,length: baseString.utf16Count)) as [NSTextCheckingResult] {
        attributed.addAttribute(NSBackgroundColorAttributeName,value: UIColor.yellowColor(),range: match.range)
    }

    textView.attributedText = attributed
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...