我目前拥有自己的NSTextView,我希望它能够自动编写一个粗体标签(#),如下所示:
这是 #NSTextView
的字符串(标签之前/之后的文本和标签的长度为 NOT 常量) 我如何在Swift(3)中做到这一点?
答案 0 :(得分:1)
请尝试以下方法。我的视图控制器有一个属性,textView指向我的故事板中的NSTextView。
import Cocoa
class ViewController: NSViewController {
@IBOutlet var textView: NSTextView!
override func viewDidLoad() {
super.viewDidLoad()
let text = "This is the string of my #NSTextView. All #hashtags should be displayed in bold."
textView.string = text
let attributes = [NSFontAttributeName : NSFont.systemFont(ofSize: 14.0)]
let range = NSRange(location: 0, length: text.characters.count)
textView.textStorage?.setAttributes(attributes, range: range)
do {
let regexString = "#(\\w*)"
let regex = try NSRegularExpression(pattern: regexString, options: [])
let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count))
for match in matches {
textView.textStorage?.setAttributes([NSFontAttributeName : NSFont.boldSystemFont(ofSize: 14.0)], range: match.range)
}
} catch let error {
print(error)
}
}
}