的自动标记部分我现在有我的NSTextView,我想这样它看起来像这样它自动写入粗体哈希标签(#):NSTextView
这是我#NSTextView串
(之前/之后的文本和标签的长度是不是常量) 我如何在Swift(3)中做到这一点?
的自动标记部分我现在有我的NSTextView,我想这样它看起来像这样它自动写入粗体哈希标签(#):NSTextView
这是我#NSTextView串
(之前/之后的文本和标签的长度是不是常量) 我如何在Swift(3)中做到这一点?
请尝试以下操作。我的视图控制器有一个属性,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)
}
}
}
呃...使用UIKit? –
除了您将通过NSTextView的textStorage对象设置文本属性之外,您可以使用NITextView完成与UITextView相同的操作。 –
请告诉我们如何。 –
做一些搜索,如何使用NSRange来设置'NSAttributedString'来将样式应用到文本的各个部分。配置完字符串后,您可以将NSTextView的'.attributedText'属性设置为您创建的字符串。 – par
向我们展示你迄今为止做了什么,而不是做出一个早期的圣诞愿望。 –