selectText of NSTextField on focus

后端 未结 5 1690
既然无缘
既然无缘 2021-02-04 10:17

Could anybody suggest a method to select all the text of an NSTextField when the user clicks it?

I did find suggestions to subclass NSTextField

5条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 11:03

    Some updates with Swift:

    import Cocoa
    
    class TextFieldSubclass: NSTextField {
        override func mouseDown(theEvent: NSEvent) {
            super.mouseDown(theEvent)
            if let textEditor = currentEditor() {
                textEditor.selectAll(self)
            }
        }
    }
    

    Or for precise selection:

    import Cocoa
    
    class TextFieldSubclass: NSTextField {
        override func mouseDown(theEvent: NSEvent) {
            super.mouseDown(theEvent)
            if let textEditor = currentEditor() {
                textEditor.selectedRange = NSMakeRange(location, length)
            }
        }
    }
    

    Swift version, works for me:

    import Cocoa
    
    class TextFieldSubclass: NSTextField {
        override func becomeFirstResponder() -> Bool {
            let source = CGEventSourceCreate(CGEventSourceStateID.HIDSystemState)
            let tapLocation = CGEventTapLocation.CGHIDEventTap
            let cmdA = CGEventCreateKeyboardEvent(source, 0x00, true)
            CGEventSetFlags(cmdA, CGEventFlags.MaskCommand)
            CGEventPost(tapLocation, cmdA)
            return true
        }
    }
    

提交回复
热议问题