[英]Replace Substring with Markdown on NSTextView in Swift
Swift 5, Xcode 11 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: 在Stack Overflow文本编辑器中,您可以选择一些文本(如下面的“ selected”),单击粗体按钮,它将替换为:
Text selected here.
...with this: ...有了这个:
Text **selected** here.
I'm trying to pull off the same thing with an NSTextView
using Swift 5. 我正在尝试使用Swift 5通过NSTextView
进行同样的事情。
I can get the selectedRange
of the text like this: 我可以这样获得文本的selectedRange
:
@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
. 我发现replaceSubrange
但它似乎只接受Range<String.Index>
,而不接受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! 谢谢!
You should use the replaceCharacters(in:with:)
method of NSText
(whose subclass NSTextView
is). 您应该使用NSText
(其子类NSTextView
是)的replaceCharacters(in:with:)
方法。
@IBAction func clickBold(_ sender: NSButton) {
let range = content.selectedRange()
let selectedText = (content.string as NSString).substring(with: range)
content.replaceCharacters(in: range, with: "**\(selectedText)**")
}
It looks like this works: 看起来像这样:
let range = content.selectedRange()
markdownText = content.string
if let index = Range(range, in: markdownText){
content.replaceCharacters(in: range, with: "**\(markdownText[index])**")
}
It provides the selected text snippet I need to wrap it in ** **
. 它提供了我需要将其包装在** **
的选定文本片段。 @MartinR's linked SO post helped me see that I can convert the string index with Range()
. @MartinR的链接SO帖子帮助我看到可以使用Range()
转换字符串索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.