无法将(Command + V)粘贴到NSTextField中

Che*_*tan 18 cocoa copy-paste objective-c nstextfield

出于某种原因,NSTextField不允许我使用它来粘贴任何内容Command+V,但是如果我右键单击并单击"粘贴",我可以粘贴到其中.为什么会发生这种情况,我该如何解决?

Awa*_*een 8

感谢这个 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)
}
Run Code Online (Sandbox Code Playgroud)

}


Che*_*tan 6

我通过将NSMenu主菜单中的"粘贴"按钮链接到第一响应者的paste:命令来修复它.

  • 除此之外我还有更多...我已经重新添加了IB的标准"菜单项 - 编辑",其中的所有命令都正确链接到第一响应者.但仍然没有得到任何键盘命令.我没有正确连接"菜单项 - 编辑"吗? (2认同)