NSTextField - undo without Edit menu. need correct solution

Hello


I removed Edit menu from my app. So I can't use copy/paste/selectall/undo/redo in NSTextField and NSTextView.


I used examples from internet to implement copy/paste/selectall/undo/redo in NSTextField/NSTextView.


private let commandKey = NSEvent.ModifierFlags.command.rawValue
private let commandShiftKey = NSEvent.ModifierFlags.command.rawValue | NSEvent.ModifierFlags.shift.rawValue
   
    override func performKeyEquivalent(with event: NSEvent) -> Bool {
        if event.type == NSEvent.EventType.keyDown {
            if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandKey {
                switch event.charactersIgnoringModifiers! {
                case "x":
                    if NSApp.sendAction(#selector(NSText.cut(_:)), to:nil, from:self) { return true }
                case "c":
                    if NSApp.sendAction(#selector(NSText.copy(_:)), to:nil, from:self) { return true }
                case "v":
                    if NSApp.sendAction(#selector(NSText.paste(_:)), to:nil, from:self) { return true }
                case "z":
                    if NSApp.sendAction(Selector(("undo:")), to:nil, from:self) { return true }
                case "a":
                    if NSApp.sendAction(#selector(NSStandardKeyBindingResponding.selectAll(_:)), to:nil, from:self) { return true }
                default:
                    break
                }
            } else if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandShiftKey {
                if event.charactersIgnoringModifiers == "Z" {
                    if NSApp.sendAction(Selector(("redo:")), to: nil, from: self) { return true }
                }
            }
        }
        return super.performKeyEquivalent(with: event)
    }

But problem .. if I write some text and do undo .. All text is removed at once. I want to make undo action natural like in all Cocoa apps. Just one or few characters are removed if I do undo. Now all text is removed.


Any suggestions how fix this problem ?


Or maybe I need again add Edit menu to better support human interface guidelines?

Replies

I found I'm not implementing undo and redo selectors ..


I changed code to:


case "z":
if NSApp.sendAction(#selector(self.undo), to:nil, from:self) { returntrue }


and


@objcfunc undo() {
        self.undoManager?.undo()
    }


But it don't work. Any hints ?

Leave your code as it was, and try adding:

Code Block swift
textField.allowsUndo = true


This presumes that your NStextField is called textField .

-[NSTextView breakUndoCoalescing] can do this