UITextView highlight all matches using swift

前端 未结 7 1462
南方客
南方客 2020-12-08 09:26

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

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 09:35

    Solved.

    this is new :

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

    i used range variable instead of highlighted range in attributedText.addAtrribute()

提交回复
热议问题