![](/img/trans.png)
[英]Getting the Y coordinate for every occurrence of a particular string in a UITextView for line numbering
[英]is it possible to find every occurrence of a string in UITextView and attribute that occurrence?
我正在尝试在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
}
该系统发送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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.