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

UITextView使用swift突出显示所有匹配项,第1张

概述我想通过搜索突出显示所有匹配单词.我写了代码,但我不能使用循环.当我搜索一个单词时,我的应用程序会找到单词并突出显示第一个单词.这是我的代码 var count = 0let attributedText = NSMutableAttributedString(attributedString: txtMetin2.attributedText)let text2 = txtArama.tex 我想通过搜索突出显示所有匹配单词.我写了代码,但我不能使用循环.当我搜索一个单词时,我的应用程序会找到单词并突出显示第一个单词.这是我的代码
var count = 0let attributedText = NSMutableAttributedString(attributedString: txtMetin2.attributedText)let text2 = txtarama.text as Nsstringlet text = txtMetin2.text as Nsstringvar range:NSRangevar 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}
总结

以上是内存溢出为你收集整理的UITextView使用swift突出显示所有匹配项全部内容,希望文章能够帮你解决UITextView使用swift突出显示所有匹配项所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1034711.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存