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
I know this is an old question, but here's an update for those who might stumble over this.
Override NSTextField and hook into becomeFirstResponder(). You won't have to worry about managing delegates or clicks. The tricky part is finding the field editor for the focused text field first before asking it to select all the text.
Objective-C
// in AutoselectOnFocusTextField.h
@interface AutoselectOnFocusTextField : NSTextField
@end
// in AutoselectOnFocusTextField.m
@implementation AutoselectOnFocusTextField
- (BOOL)becomeFirstResponder {
if (![super becomeFirstResponder]) {
return NO;
}
NSText* fieldEditor = [self currentEditor];
if (fieldEditor != nil) {
[fieldEditor performSelector:@selector(selectAll:) withObject:self afterDelay:0.0];
}
return YES;
}
@end
Swift
class AutoselectOnFocusTextField: NSTextField {
override func becomeFirstResponder() -> Bool {
guard super.becomeFirstResponder() else {
return false
}
if let editor = self.currentEditor() {
editor.perform(#selector(selectAll(_:)), with: self, afterDelay: 0)
}
return true
}
}