2

I have a question about using NSViewController and switching between views. I have a Cocoa application where I have a window. The idea with the window is that it will display a number of views one by one where each view is stored in a separate XIB file. Each view has a corresponding NSViewController. I have made a minimal example of what I'm doing where only the first view is loaded.

@interface MyWindowController : NSWindowController {
    NSViewController *currentViewController;
}
@property (assign) IBOutlet NSView *targetView;
@end

@implementation MyWindowController

@synthesize targetView;

- (id)init
{
    return [super initWithWindowNibName:@"MyWindow"];
}

- (void)dealloc
{
    [currentViewController release];
    [super dealloc];
}

- (void)windowDidLoad
{
    [super windowDidLoad];

    currentViewController = [[NSViewController alloc] initWithNibName:@"FirstView" bundle:nil];
    [self.targetView addSubview:currentViewController.view];
    [currentViewController.view setFrame:targetView.bounds];
}

@end

When the window is loaded the view from FirstView.xib is also loaded and the view is displayed in the window. In this case the loaded view only has a text field and I would like the text field to be highlighted so that input can be written to it directly without the user having to click on it but I can't figure out how to do that. Is it possible to have the text field selected when the view is loaded?

After reading the documentation I have found that I probably want to set the window's initialFirstResponder to the text field, but I can't find how to do that when the text field is in a different XIB file than the window.

Brian Norh
  • 85
  • 1
  • 4

1 Answers1

1

Whenever you add/replace a subview and want it to be the first responder, have your window controller make the view the first responder of the window managed by the window controller:

[[self window] makeFirstResponder:currentViewController.view];

You’ll want to do this in both -windowDidLoad and whichever other methods add/replace subviews.

  • For the record by setting not just the view but its netKeyView to become the first responder and set the corresponding outlet in IB to the text field I could have the text field selected after the view was loaded. Otherwise the view itself became the first responder the the text field would be selected when tab was pressed. – Brian Norh Jun 17 '11 at 05:30
  • @Brian True; that depends on what the subview actually is. –  Jun 17 '11 at 06:37