Ezekiel
Ezekiel

Reputation: 101

Automatically markup part of NSTextView

I currently have my NSTextView and I want it to automatically write a hashtag (#) in bold so it looks like this:

This is the string of my #NSTextView

(The text before/after and the length of the hashtag is NOT constant) how do I do that in Swift (3)?

Upvotes: 1

Views: 716

Answers (1)

Justin Garcia
Justin Garcia

Reputation: 326

Please try the following. My view controller has a single property, textView that points to an NSTextView in my storyboard.

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)
        }
    }
}

Upvotes: 2

Related Questions