我查看了其他 SO 问题,但看不到我需要的帮助:我有一个 Cocoa 应用程序,其 NSViewControllers 子类在 NSTabView 中。
一切正常,除了 - 当我第一次运行应用程序时,Tab 0 内容不显示。当我选择选项卡 1,然后选项卡 0,选项卡 1 显示,选项卡 0 显示正常。
我需要一些关于如何初始化选项卡视图的建议,因为我想我正在做一些奇怪的事情。
到目前为止,这就是我正在做的事情:
- (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;
}
更新,彼得·霍西(Peter Hosey)发表了很好的评论,我的工作代码如下:
- (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];
}