我正在尝试为 textview 字符串的所有出现(不仅仅是第一次出现)着色,但是当我进入循环时,我得到一个无法调用 rangeOfString
参数。
我查看了关于 Swift 2 的 rangeOfString:options:range
文档,它看起来非常相似。我不太确定自己做错了什么。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
func textView(textView: UITextView){
if textView == self.textView {
let nsString = textView.text as NSString
let stringLength = textView.text.characters.count
var range = NSRange(location: 0, length: textView.text.characters.count)
let searchString = textView.text
let text = NSMutableAttributedString(string: textView.text)
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, stringLength))
textView.attributedText = text
while(range.location != NSNotFound) {
range = (textView.text as NSString).rangeOfString(searchString, options: NSStringCompareOptions, range: range)
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: nsString.rangeOfString("hello"))
}
}
}
}
最佳答案
您似乎在尝试突出显示搜索栏中的用户输入。我是这样做的:
func highlightedText(text: NSString, inText: NSString, var withColor: UIColor?) -> NSMutableAttributedString {
var attributedString = NSMutableAttributedString(string:inText as String)
let range = (inText.lowercaseString as NSString).rangeOfString(text.lowercaseString as String)
if withColor == nil {
if let color = globalTint() {
withColor = color
} else {
withColor = UIColor.redColor()
}
}
attributedString.addAttribute(NSForegroundColorAttributeName, value: withColor! , range: range)
return attributedString
}
...
textView.attributedText = highlightedText("string", inText: titleText, color: nil)
关于ios - 尝试为所有出现的 TextView 字符串着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32519494/