首页 > 解决方案 > 在不破坏撤消堆栈的情况下在 NSTextView 中附加文本

问题描述

我有一个基于 NSTextView 的应用程序,其中有各种更改文本的命令。为了替换一部分,我使用以下代码段:

if ([textView shouldChangeTextInRange:range replacementString:string]) { //string
  [textStorage beginEditing];
  [textStorage replaceCharactersInRange:range withAttributedString:attributedString];
  [textStorage endEditing];
  [textView didChangeText];
}

当我想在文本视图的末尾追加时,我的问题就开始了。在那种情况下,我不能使用shouldChangeTextInRange:range replacementString:string,所以我使用:

textView.textStorage?.beginEditing()
self.textView.textStorage?.append(NSAttributedString(string: string))
self.textView.scrollToEndOfDocument(nil)
textView.textStorage?.endEditing()
textView.didChangeText()

虽然它适用于属性,但 Undo 完全中断。知道如何解决这个问题吗?

标签: swiftcocoansattributedstringnstextviewnstextstorage

解决方案


推荐阅读