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

时间:2014-08-27 10:47:25

标签: swift uitextview

我想用搜索突出显示所有匹配词。我写了代码,但我不能使用循环。当我搜索一个单词时,我的应用程序会找到单词并突出显示第一个单词。这是我的代码

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)")

我很聪明。抱歉编码不好。我的代码找到匹配数,但我怎么能突出显示所有匹配谢谢

7 个答案:

答案 0 :(得分:18)

基于强制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
}

答案 1 :(得分:5)

您可以使用以下函数传递搜索输入和当前内容。这将返回您可以在NSAttributedString?

中设置的TextView

Swift 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
    }
}

编辑:

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

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
    }
}

答案 2 :(得分:2)

Uitextview突出显示所有匹配词swift 3.0

 let searchString = "Lorem Ipsum"
 let baseString = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard .Containing LOREM IPSUM passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem IPSUM"



let attributed = NSMutableAttributedString(string: baseString)
    do
    {
        let regex = try! NSRegularExpression(pattern: searchString,options: .caseInsensitive)
        for match in regex.matches(in: baseString, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: baseString.characters.count)) as [NSTextCheckingResult] {
            attributed.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellow, range: match.range)
        }
        self.txtView.attributedText = attributed
    }

click here to see image

答案 3 :(得分:2)

改进的Swift 4.2定制解决方案

extension NSAttributedString {
    convenience init(base: String,
                     keyWords: [String],
                     foregroundColor: UIColor,
                     font: UIFont,
                     highlightForeground: UIColor,
                     highlighBackground: UIColor) {
        let baseAttributed = NSMutableAttributedString(string: base, attributes: [NSAttributedString.Key.font: font,
                                                                                  NSAttributedString.Key.foregroundColor: foregroundColor])
        let range = NSRange(location: 0, length: base.utf16.count)
        for word in keyWords {
            guard let regex = try? NSRegularExpression(pattern: word, options: .caseInsensitive) else {
                continue
            }

            regex
                .matches(in: base, options: .withTransparentBounds, range: range)
                .forEach { baseAttributed
                    .addAttributes([NSAttributedString.Key.backgroundColor: highlighBackground,
                                    NSAttributedString.Key.foregroundColor: highlightForeground],
                                   range: $0.range) }
        }
        self.init(attributedString: baseAttributed)
    }
}

答案 4 :(得分:1)

快速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
    }
}

答案 5 :(得分:1)

我想对@Barath和@Bruno Paulino提供的解决方案进行一点改进,因为该解决方案不适用于 {} []()'“ 的转义字符 strong>,此解决方案适用于转义字符,该解决方案以SWIFT 5编写。

func generateAttributedString(with searchTerm: String, targetString: NSAttributedString) -> NSAttributedString? {
    let attributedString = NSMutableAttributedString(attributedString: targetString)
    do {

        let regex = try NSRegularExpression(pattern:  NSRegularExpression.escapedPattern(for: searchTerm).trimmingCharacters(in: .whitespacesAndNewlines).folding(options: .regularExpression, locale: .current), options: .caseInsensitive)
        let range = NSRange(location: 0, length: targetString.string.utf16.count)
        attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.clear, range: range)
        for match in regex.matches(in: targetString.string.folding(options: .regularExpression, locale: .current), options: .withTransparentBounds, range: range) {
            attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.yellow, range: match.range)
        }
        return attributedString
    } catch {
        NSLog("Error creating regular expresion: \(error)")
        return nil
    }
}

答案 6 :(得分:0)

解决。

这是新的:

var count = 0
let attributedText = NSMutableAttributedString(attributedString: txtMetin2.attributedText)
let text2 = txtArama.text as NSString
let text = txtMetin2.text as NSString
println("\(text.length)")
println("\(text2.length)")
var range:NSRange
var checker:NSString = ""

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

我在attributionText.addAtrribute()

中使用了范围变量而不是突出显示的范围
相关问题