【问题标题】:Automatically markup part of NSTextView自动标记部分 NSTextView
【发布时间】:2017-03-04 16:08:38
【问题描述】:

我目前有我的 NSTextView,我希望它自动以粗体写一个主题标签 (#),所以它看起来像这样:

这是我的#NSTextView

的字符串

(之前/之后的文本和主题标签的长度是NOT常量) 我如何在 Swift (3) 中做到这一点?

【问题讨论】:

  • 搜索一下如何使用NSRange 设置NSAttributedString 以将样式应用于文本的各个部分。配置好字符串后,您可以将NSTextView.attributedText 属性设置为您创建的字符串。
  • 向我们展示你到目前为止所做的事情,而不是提前许下圣诞愿望。

标签: swift macos nstextview


【解决方案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)
        }
    }
}

【讨论】:

  • 呃...使用 UIKit?
  • 你可以用 NSTextView 做和我用 UITextView 做的一样的事情,除了你将通过 NSTextView 的 textStorage 对象来设置文本属性。
  • 请告诉我们怎么做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
  • 2020-02-14
  • 2017-09-30
相关资源
最近更新 更多