selectText of NSTextField on focus

后端 未结 5 1698
既然无缘
既然无缘 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 10:49

    I like Konstantin's solution, but that one will select on every mouse down. Here's a variation I'm using to select in mouseDown method, but only if it just became the first responder:

    class SelectingTextField: NSTextField {
    
        var wantsSelectAll = false
    
        override func becomeFirstResponder() -> Bool {
            wantsSelectAll = true
    
            return super.becomeFirstResponder()
        }
    
        override func mouseDown(with event: NSEvent) {
            super.mouseDown(with: event)
    
            if wantsSelectAll {
                selectText(self)
                wantsSelectAll = false
            }
        }
    }
    

提交回复
热议问题