[swift]它是字符串的可能发生在 UITextView 和属性中找到每个出现?

标签: UITextView ios Swift
发布时间: 2016/2/29 17:36:39
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我想查找每个出现的字符串在 UITextView 和属性中,但我的整个 textView 属性后该字符串的第一个匹配。可能找到"你好"每次出现的位置和属性他们不用归于整个 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:

系统发送 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
}
官方微信
官方QQ群
31647020