UITextView 使用 swift 突出显示所有匹配项 [英] UITextView highlight all matches using swift
本文介绍了UITextView 使用 swift 突出显示所有匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过搜索突出显示所有匹配的单词.我写了代码,但我不能使用循环.当我搜索一个单词时,我的应用程序会查找单词并仅突出显示第一个单词.这是我的代码
I want to highlight all matches word with searching. I wrote code but I couldn't use a loop. When i search a word, my app find words and highlight only first word. here is my code
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)")
我是 swift 的新手.抱歉糟糕的编码.我的代码找到匹配计数但我如何突出显示所有匹配谢谢
i am very new at swift. sorry for bad coding. my codes find matches count but how can i highlight all matches thank you
推荐答案
Obligatory 基于 NSRegularExpression 的解决方案.
Obligatory NSRegularExpression based solution.
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 突出显示所有匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文