Quantcast
Viewing latest article 3
Browse Latest Browse All 3

Replace Substring with Markdown on NSTextView in Swift

Swift 5, Xcode 11

In a Stack Overflow text editor, you can select some text (like "selected" below), click the bold button, and it replaces:

Text selected here.

...with this:

Text **selected** here.

I'm trying to pull off the same thing with an NSTextView using Swift 5.

I can get the selectedRange of the text like this:

@IBAction func clickBold(_ sender: NSButton) {
  let range = content.selectedRange() //content is my NSTextView
}

But I can't figure out how to proceed from here. I found replaceSubrange but it seems to accept only a Range<String.Index> and not an NSRange.

@IBAction func clickBold(_ sender: NSButton) {
  let range = content.selectedRange() //content is my NSTextView
  var markdownText = content.string
  markdownText.replaceSubrange(range, with: "**\(markdownText)**") 
}

Has anyone done this before and can help me see what I'm missing? Thanks!


Viewing latest article 3
Browse Latest Browse All 3

Trending Articles