Can't paste (Command+V) into an NSTextField

Viewed 7905

For some reason, an NSTextField isn't allowing me to paste anything into it using Command+V, though I can paste into it if I right-click and click 'Paste'. Why is this happening and how do I fix it?

4 Answers

I fixed it by linking the "Paste" button in my NSMenu Main Menu to the First Responder's paste: command.

What happens when you select "Edit > Paste" from your application's main menu?

Did you:

  • Assign a key equivalent to any of your controls (NSButtons, NSMenuItems, ...) that are responding before the Main Menu

-- or --

  • Delete the whole Menu
  • the Edit NSMenuItem
  • the Paste NSMenuItem The "Paste" Shortcut is a key equivalent of the "Paste" NSMenuItem

Thanks to this Making copy & paste work with NSTextField

final class EditableNSTextField: NSTextField {

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(NSResponder.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)
}

}

Related