I have looked at other SO questions, but cannot see the help I need: I have a Cocoa app with NSViewControllers subclassed in an NSTabView.
Everything works except for - when I first run the app, Tab 0 contents do not show. When I select tab 1, then tab 0, Tab 1 shows, and Tab 0 shows ok.
I need some advice on how to initialize the tab view, as I guess I'm doing something wonky.
This is what I'm doing so far:
- (void)windowDidLoad
{
NSLog(@"%s", __FUNCTION__);
NSViewController *newController = nil;
newController = [[FirstViewController alloc]
initWithNibName:@"FirstViewController" bundle:nil];
NSTabViewItem *item;
[[self aTabView] selectFirstTabViewItem:newController];
newController.view.frame = aTabView.contentRect;
[item setView:firstViewController.view];
self.currentViewController = newController;
}
UPDATE, with great comments from Peter Hosey, I have working code as follows:
- (void)windowDidLoad
{
NSLog(@"%s", __FUNCTION__);
firstViewController = [[FirstViewController alloc]
initWithNibName:@"FirstViewController" bundle:nil];
secondViewController = [[SecondViewController alloc]
initWithNibName:@"SecondViewController" bundle:nil];
thirdViewController = [[ThirdViewController alloc]
initWithNibName:@"ThirdViewController" bundle:nil];
NSTabViewItem *item;
if (firstViewController != nil) {
item = [aTabView tabViewItemAtIndex:0];
[item setView:[[self firstViewController] view]];
//[firstViewController.view.frame = aTabView.contentRect];
self.currentViewController = firstViewController;
}
}
- (BOOL)switchViewController:(NSTabView*)tabView item:(NSTabViewItem*)nextItem {
NSLog(@"%s", __FUNCTION__);
NSViewController *newController = nil;
newController.view = NO;
// assume a different identifier has been assigned to each tab view item in IB
itemIndex = [tabView indexOfTabViewItemWithIdentifier:[nextItem identifier]];
switch (itemIndex) {
case 0:
newController = firstViewController;
break;
case 1:
newController = secondViewController;
break;
case 2:
newController = thirdViewController;
break;
}
if (newController != nil) {
[nextItem setView:newController.view];
newController.view.frame = tabView.contentRect;
self.currentViewController = newController;
/*
NSLog(@"%s: myTabView.contentRect=%@ currentViewController.view.frame=%@",
__FUNCTION__, NSStringFromRect(aTabView.contentRect),
NSStringFromRect(currentViewController.view.frame));
*/
return YES;
}
else {
// report error to user here
NSLog(@"Can't load view for tab %ld", (long)itemIndex);
return NO;
}
}
- (BOOL)tabView:(NSTabView*)tabView shouldSelectTabViewItem:(NSTabViewItem*)tabViewItem {
return [self switchViewController:tabView item:tabViewItem];
}