ios - UITextView/NSAttribute:检测单词是否以特定符号开头
问题描述
我一直在寻找一种方法来更改 aUITextView
当单词以"@"
or开头时的文本"#"
。我在下面的 StackOverflow 上找到了这段代码片段"Hello"
,如果你输入或"World"
.
如何调整此代码,以便它检测单词是否以“@”或“#”开头,后跟空格前的任意数量的字符,并应用相同的样式?
如果用户以orUITextView
开始“单词”,结果将导致文本的颜色发生变化。IE:"@"
"#"
快速的棕色#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
}
}
}
}
解决方案
假设您保留#
或@
在文本中,您可以修改 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: UIColor.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,修复了一些错误,删除了一些冗余代码并添加了一些代码来改变颜色。
推荐阅读
- linux - 在 VS Code 上使用 vim 扩展,但保留原始绑定
- xamarin.android - ADB1000:System.ArgumentOutOfRangeException:长度不能小于零。没有明显的原因
- javascript - 获取“计数”变量而不是“对象鼠标事件”
- php - 如何在蓝色主机中配置 php 电子邮件以使用 mail() 函数?
- node.js - 我面临在猫鼬中链接 .populate() 方法的问题
- c++ - 如何在过剩中设置左上角窗口图标?
- geolocation - 用于为包含纬度/经度中心点的发布请求返回 geoJSON 圆形文件的 API
- symfony - Symfony 4 使用带有额外属性的连接表形成多对多
- c++ - 捕获/处理 AngelScript 函数中抛出的异常
- c# - PDF 文件不在 Windows 窗体的 webBrowser 控件中