我想通過搜索來突出顯示所有匹配的詞。我寫了代碼,但我不能使用循環。當我搜索一個單詞時,我的應用程序找到單詞並僅突出顯示第一個單詞。這裏是我的代碼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)")
我在swift很新。抱歉代碼不正確。我的代碼找到匹配數,但我如何突出顯示所有匹配謝謝
非常感謝你:) – ardacankaya 2014-08-27 12:43:16
當我搜索符號像點和問號時,它不起作用。「 '?' – 2016-04-19 14:36:52
@ArunKumarP它是一個正則表達式,因此您需要在搜索字符串中將它們轉義。例如'stuff \\?'或'stuff \\。'。 – 2016-04-19 15:29:24