Cocoa Keyboard Shortcuts in Dialog without an Edit Menu

前端 未结 16 1275
Happy的楠姐
Happy的楠姐 2020-12-04 07:28

I have an LSUIElement application that displays a menubar status item. The application can display a dialog window that contains a text field.

If the u

16条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 07:51

    Based on Thomas Kilian's answer, you can actually create an extension for NSTextField

    let commandKey = NSEvent.ModifierFlags.command.rawValue
    let commandShiftKey = NSEvent.ModifierFlags.command.rawValue | NSEvent.ModifierFlags.shift.rawValue
    
    extension NSTextField {
        func performEditingKeyEquivalent(with event: NSEvent) -> Bool {
            guard event.type == NSEvent.EventType.keyDown else { return false }
    
            if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandKey {
                if let character = event.charactersIgnoringModifiers {
                    switch character {
                    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 false
        }
    }
    

    In the followingg example, one can actually replace NSTextField with any of the NSTextField inheriting classes (e.g NSSearchField, NSSecureTextField) to have the new functionality

    class SearchField: NSTextField {
        override func performKeyEquivalent(with event: NSEvent) -> Bool {
            if performEditingKeyEquivalent(with: event) {
                return true
            }
    
            return super.performEditingKeyEquivalent(with: event)
        }
    }
    

提交回复
热议问题