Swift 在NSTextView中追加文本,同时不中断撤消堆栈
我有一个基于NSTextView的应用程序,其中有各种命令可以更改文本。为了替换部分,我使用以下代码段:Swift 在NSTextView中追加文本,同时不中断撤消堆栈,swift,cocoa,nsattributedstring,nstextview,nstextstorage,Swift,Cocoa,Nsattributedstring,Nstextview,Nstextstorage,我有一个基于NSTextView的应用程序,其中有各种命令可以更改文本。为了替换部分,我使用以下代码段: if ([textView shouldChangeTextInRange:range replacementString:string]) { //string [textStorage beginEditing]; [textStorage replaceCharactersInRange:range withAttributedString:attributedString];
if ([textView shouldChangeTextInRange:range replacementString:string]) { //string
[textStorage beginEditing];
[textStorage replaceCharactersInRange:range withAttributedString:attributedString];
[textStorage endEditing];
[textView didChangeText];
}
当我想在textview的末尾追加内容时,我的问题就开始了。在这种情况下,我不能使用shouldChangeTextInRange:range replacementString:string
,因此我使用:
textView.textStorage?.beginEditing()
self.textView.textStorage?.append(NSAttributedString(string: string))
self.textView.scrollToEndOfDocument(nil)
textView.textStorage?.endEditing()
textView.didChangeText()
虽然它对属性很有效,但“撤消”会完全中断。你知道如何解决这个问题吗?提示:有效地使用
TextView
类的selectedRange
方法。为什么你不能使用shouldChangeTextInRange:replacementString:
?我终于听从了你的建议,它成功了。谢谢