selectText of NSTextField on focus

Michael C picture Michael C · Feb 3, 2010 · Viewed 8.5k times · Source

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 and then use mouseDown or firstResponder,` but it's beyond my skill for now. So I was hoping either there would be an easier solution or somebody might be kind enough to detail the steps required.

Answer

Rob Keniger picture Rob Keniger · Feb 4, 2010

There isn't an easier solution, you need to subclass NSTextField to do what you want. You will need to learn how to handle subclassing if you are to do anything useful in Cocoa.

Text fields can be relatively complex to subclass because an NSTextField uses a separate NSTextView object called the Field Editor to handle the actual editing. This text view is returned by the NSWindow object for the NSTextField and it is re-used for all text fields on the page.

Like any NSResponder subclass, NSTextField responds to the methods -acceptsFirstResponder and -becomeFirstResponder. These are called when the window wants to give focus to a particular control or view. If you return YES from both these methods then your control/view will have first responder status, which means it's the active control. However, as mentioned, an NSTextField actually gives the field editor first responder status when clicked, so you need to do something like this in your NSTextField subclass:

@implementation MCTextField
- (BOOL)becomeFirstResponder
{
    BOOL result = [super becomeFirstResponder];
    if(result)
        [self performSelector:@selector(selectText:) withObject:self afterDelay:0];
    return result;
}
@end

This first calls the superclass' implementation of -becomeFirstResponder which will do the hard work of managing the field editor. It then calls -selectText: which selects all the text in the field, but it does so after a delay of 0 seconds, which will delay until the next run through the event loop. This means that the selection will occur after the field editor has been fully configured.