是否有可能在UITextView中找到每个字符串的出现并将该事件归因于该属性?

时间:2015-09-22 18:13:12

标签: ios swift cocoa-touch uitextview

我试图在UITextView中找到每个字符串的出现并将该事件归因于该事件,但是在第一次出现该字符串后,我将整个textView属性化。是否有可能找到每个“hello”出现的位置并将其归因于不归因于整个textView

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

            if textView == self.textView {

        let nsString = textView.text as NSString
        let end = textView.text.characters.count
        let range = NSMakeRange(0, end) as NSRange

        let hString = nsString.rangeOfString("hello")
        let text = NSMutableAttributedString(string: textView.text)

        let cTv = textView.attributedText.mutableCopy() as! NSMutableAttributedString


                if hString.length > 0{


           text.addAttribute(NSForegroundColorAttributeName, value: UIColor.magentaColor(), range: range)


                    cTv.replaceCharactersInRange(range, withAttributedString: text)

        }


                textView.attributedText = text

    }
    return true

}

1 个答案:

答案 0 :(得分:2)

系统在修改textView(_:shouldChangeTextInRange:replacementText:)之前发送textView.text 。您可能最好不要实施textViewDidChange(_:),系统在修改textView.text之后发送

func textViewDidChange(textView: UITextView) {
    let text = textView.text as NSString
    let richText = NSMutableAttributedString(string: text as String)
    var searchRange = NSMakeRange(0, text.length)
    while true {
        let range = text.rangeOfString("hello", options: [], range: searchRange)
        if range.location == NSNotFound {
            break
        }
        richText.addAttribute(NSForegroundColorAttributeName, value: UIColor.magentaColor(), range: range)
        searchRange.location = range.location + range.length
        searchRange.length = text.length - searchRange.location
    }
    textView.attributedText = richText
}