简体   繁体   English

如何从 NSDocument 中分离 NSTextView 的撤消管理器?

[英]How to detach NSTextView's undo manager from NSDocument?

I have an NSDocument that is in a non-directly editable format, it's a description of something in XML.我有一个非直接可编辑格式的 NSDocument,它是对 XML 中某些内容的描述。 The NSWindow has a settings view controller associated with it which manipulates the data in the document just fine, undo works as expected, save, etc. Now also in the NSWindow is an NSTextView, which the user can enter some text into, but is not part of the content of the document, it's used only as temporary text. NSWindow 有一个设置视图 controller 与之关联,它可以很好地处理文档中的数据,撤消按预期工作,保存等。现在在 NSWindow 中还有一个 NSTextView,用户可以在其中输入一些文本,但不是文档内容的一部分,它仅用作临时文本。 Of course I want to support undo for this text too, so I have the "Undo" checkmark enabled in Interface Builder for this NSTextView, and undo works just fine.当然我也想支持这个文本的撤消,所以我在 Interface Builder 中为这个 NSTextView 启用了“撤消”复选标记,撤消工作得很好。

Now comes the rub: the NSDocument is getting marked as dirty when the NSTextView is modified.现在问题来了:修改 NSTextView 时,NSDocument 被标记为脏。 Because this is temporary text, I don't want the user to be nagged to save changes to the document, that really are not part of the document.因为这是临时文本,我不希望用户被唠叨以保存对文档的更改,这实际上不是文档的一部分。

How do I detach the NSTextView from the responder chain leading up to the NSDocument's undo manager instance?如何将 NSTextView 从导致 NSDocument 的撤消管理器实例的响应程序链中分离出来? Simply providing a new instance of NSUndoManager doesn't solve it, because it just goes up the responder chain to NSDocument as well.简单地提供一个新的 NSUndoManager 实例并不能解决它,因为它也只是沿着响应者链上升到 NSDocument 。

extension InputViewController: NSTextViewDelegate {
    func undoManager(for view: NSTextView) -> UndoManager? {
        return myUndoManager
    }
}

I'm pretty sure you'd need to override the undoManager property of the window's view controller, not the text field's delegate.我很确定您需要覆盖窗口视图 controller 的undoManager属性,而不是文本字段的委托。

However, to simply make your document/window permanently non-editable all you need to do is override either the documentEdited property so it always returns false , or override updateChangeCount so it ignores requests to record changes.但是,要简单地使您的文档/窗口永久不可编辑,您需要做的就是覆盖documentEdited属性使其始终返回false ,或覆盖updateChangeCount使其忽略记录更改的请求。

Thanks to James Bucanek's comment about overriding updateChangeCount , I was able to do something like this in my NSDocument subclass:感谢 James Bucanek 关于覆盖updateChangeCount的评论,我能够在我的NSDocument子类中做这样的事情:

    override func updateChangeCount(_ change: NSDocument.ChangeType) {
        if !suppressChangeCount {
            super.updateChangeCount(change)
        } else {
            suppressChangeCount = false
        }
    }

Thus allowing undo/redo to work in my InputViewController keycode handler without dirtying the document.因此允许撤消/重做在我的InputViewController键码处理程序中工作,而不会弄脏文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM