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

ard*_*aya 9 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)")
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*lum 19

基于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
}
Run Code Online (Sandbox Code Playgroud)


Bru*_*ino 5

您可以使用以下函数传递搜索输入和当前内容.这将返回NSAttributedString?你可以设置的TextView

斯威夫特3

func generateAttributedString(with searchTerm: String, targetString: String) -> NSAttributedString? {
    let attributedString = NSMutableAttributedString(string: targetString)
    do {
        let regex = try NSRegularExpression(pattern: searchTerm, options: .caseInsensitive)
        let range = NSRange(location: 0, length: targetString.utf16.count)
        for match in regex.matches(in: targetString, options: .withTransparentBounds, range: range) {
            attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 16, weight: UIFontWeightBold), range: match.range)
        }
        return attributedString
    } catch _ {
        NSLog("Error creating regular expresion")
        return nil
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

用变音符号不敏感选项突出显示:

func generateAttributedString(with searchTerm: String, targetString: String) -> NSAttributedString? {

    let attributedString = NSMutableAttributedString(string: targetString)
    do {
        let regex = try NSRegularExpression(pattern: searchTerm.trimmingCharacters(in: .whitespacesAndNewlines).folding(options: .diacriticInsensitive, locale: .current), options: .caseInsensitive)
        let range = NSRange(location: 0, length: targetString.utf16.count)
        for match in regex.matches(in: targetString.folding(options: .diacriticInsensitive, locale: .current), options: .withTransparentBounds, range: range) {
            attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 16, weight: UIFontWeightBold), range: match.range)
        }
        return attributedString
    } catch {
        NSLog("Error creating regular expresion: \(error)")
        return nil
    }
}
Run Code Online (Sandbox Code Playgroud)


Bar*_*ath 5

斯威夫特 4 & 5

func generateAttributedString(with searchTerm: String, targetString: String) -> NSAttributedString? {

    let attributedString = NSMutableAttributedString(string: targetString)
    do {
        let regex = try NSRegularExpression(pattern: searchTerm.trimmingCharacters(in: .whitespacesAndNewlines).folding(options: .diacriticInsensitive, locale: .current), options: .caseInsensitive)
        let range = NSRange(location: 0, length: targetString.utf16.count)
        for match in regex.matches(in: targetString.folding(options: .diacriticInsensitive, locale: .current), options: .withTransparentBounds, range: range) {
            attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.bold), range: match.range)
        }
        return attributedString
    } catch {
        NSLog("Error creating regular expresion: \(error)")
        return nil
    }
}
Run Code Online (Sandbox Code Playgroud)