简体   繁体   中英

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. 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. 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.

Now comes the rub: the NSDocument is getting marked as dirty when the NSTextView is modified. 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? Simply providing a new instance of NSUndoManager doesn't solve it, because it just goes up the responder chain to NSDocument as well.

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.

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.

Thanks to James Bucanek's comment about overriding updateChangeCount , I was able to do something like this in my NSDocument subclass:

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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