我一直在寻找一种方法来更改单词UITextView
或"@"
开头的"#"
中的文本。我在下面的StackOverflow上找到了this code snippet,如果您键入"Hello"
或"World"
,则可以完美运行。
如何调整此代码,以便它可以检测到单词以“ @”或“#”开头,后跟空格之前的任意数量的字符,并应用相同的样式?
如果用户以UITextView
或"@"
开头“单词”,则结果将导致"#"
中文本的颜色发生变化。即:
棕色的 #fox 跳过了 @lazydog 。
func textViewDidChange(_ textView: UITextView) {
let defaultAttributes = mediaDescription.attributedText.attributes(at: 0, effectiveRange: nil)
let attrStr = NSMutableAttributedString(string: textView.text, attributes: defaultAttributes)
let inputLength = attrStr.string.count
let searchString : NSArray = NSArray.init(objects: "hello", "world")
for i in 0...searchString.count-1
{
let string : String = searchString.object(at: i) as! String
let searchLength = string.count
var range = NSRange(location: 0, length: attrStr.length)
while (range.location != NSNotFound) {
range = (attrStr.string as NSString).range(of: string, options: [], range: range)
if (range.location != NSNotFound) {
attrStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location: range.location, length: searchLength))
attrStr.addAttribute(NSAttributedStringKey.font, value: UIFont(name: "Karla-Regular", size: 16.0)!, range: NSRange(location: range.location, length: searchLength))
range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
textView.attributedText = attrStr
}
}
}
}
答案 0 :(得分:3)
假设您在文本中保留#
或@
,则可以修改Larme评论中的答案:
let regex = try! NSRegularExpression(pattern: "(?:#|@)\\w+", options: [])
func textViewDidChange(_ textView: UITextView) {
let attrStr = NSMutableAttributedString(attributedString: textView.attributedText ?? NSAttributedString())
let plainStr = attrStr.string
attrStr.addAttribute(.foregroundColor, value: textView.textColor ?? .black, range: NSRange(0..<plainStr.utf16.count))
let matches = regex.matches(in: plainStr, range: NSRange(0..<plainStr.utf16.count))
for match in matches {
let nsRange = match.range
let matchStr = plainStr[Range(nsRange, in: plainStr)!]
let color: UIColor
if matchStr.hasPrefix("#") {
color = .red
} else {
color = .blue
}
attrStr.addAttribute(.foregroundColor, value: color, range: nsRange)
}
textView.attributedText = attrStr
}
我只是更改了模式,以适应Swift 4.1,修复了一些错误,删除了一些冗余代码,并添加了一些代码来更改颜色。