Search code examples
objective-cmacoscocoapopoverfirst-responder

How to handle first responder status for NSTextField subclass?


I'm working on a project which needs a special text field to edit byte values. My current solution is a dedicated readonly textfield and a "..." button to open a popover as shown in the image below:

The current solution, popover

Now I try to make my solution more user friendly. My goals are these:

  • If the text field gets the first responder status, the popover automatically opens.
  • The complete text is selected.
  • If the user leaves the text field with tab or selecting any field outside of the popover, the popover should automatically close.
  • If the user types any valid number and suffix the byte value is updated (e.g. "10 GB")

Currently I'm a little bit clueless. My questions are these:

  • Where is the best location to detect in in the subclass when the text field got first responder?
  • How can I detect when the field resigns being first responder?
  • Are there other, simpler solutions?

Solution

  • I could implement everything using - (BOOL)becomeFirstResponder as a hook to display the popover and observing the first responder to automatically hide the popover:

    - (void)viewDidMoveToWindow
    {
        [super viewDidMoveToWindow];
        [self.window addObserver:self forKeyPath:NSStringFromSelector(@selector(firstResponder)) options:0 context:NULL];
    }
    

    As a start point, I published a working project with the classes on GitHub (MIT License):

    Project on GitHub