Search code examples
cocoanstextviewfirst-responder

NSTextView won't become first responder


Here's the layout of my little test app:

  1. AppDelegate owns WindowController.
  2. WindowController owns CustomTextContainerView.
  3. CustomTextContainerView owns an NSScrollView which embeds MyCustomTextView (an NSTextView subclass).

The xibs for both the standard MainMenu and my window controller are relatively empty. My window controller's -windowDidLoad looks like this:

- (void)windowDidLoad {
    [super windowDidLoad];
    // create CustomTextContainerView
    [[self window] setContentView:self.customTextContainerView];
}

What I'm trying to do is set first responder to the textView, but I've tried everything I can think of to get this to work.

I've made it so CustomTextContainerView just forwards -becomeFirstResponder on to its textView. I've tried calling it directly on both the container and the textView but I can't get it to become first responder automatically.

Note: The user can still click in the text area and start typing, but what I'm trying to do is set first responder status automatically so I don't have to click before I start typing. What am I missing?


Solution

  • To force the first responder for a window, call this:

    [[self window] makeFirstResponder:self.customTextContainerView];
    

    (This assumes that everything else necessary for first-responder status is enabled, e.g. the view can't have overridden acceptsFirstResponder to return NO.)