0

我以编程方式创建了一个带有视图等的 TabBarController。现在我想在按钮按下时显示这个 TabBarController。我怎么做?目前我以模态方式展示它,但它不起作用 - 引发 sigtrap 错误。

这是我的 TabBarController 代码

@implementation TabBarViewController

- (void) loadView
{
    HomeViewController * homeViewController = [[HomeViewController alloc]initWithNibName:@"HomeViewController" bundle:nil];

    UITabBarController *tabBarController = [[UITabBarController alloc] init];
tabBarController.view.frame = CGRectMake(0, 0, 320, 460);

   // Set each tab to show an appropriate view controller
   [tabBarController setViewControllers:[NSArray arrayWithObjects:homeViewController, homeViewController, nil]];
   [self.view addSubview:tabBarController.view];
   [homeViewController release];
   [tabBarController release];
}

这是我从 mainViewController 的 Button Press 事件访问此 tabBarController 的代码 -

 - (IBAction)quickBrowse:(UIButton *)sender
{
    TabBarViewController * tabBarController = [[TabBarViewController alloc]init];
    [self presentModalViewController:tabBarController animated:YES];
    [tabBarController release];
}
4

1 回答 1

1

如果您不使用 IB 并且想要手动创建视图,则只应覆盖方法 loadView。当你这样做时,你必须将你的根视图分配给 UIViewController 的视图属性。

我相信在你的情况下你不需要重写这个方法,你可以使用 viewDidLoad 方法来创建你的 UITabBarController 并将它存储在一个变量中,所以当事件被调用时,你需要做的就是将变量传递给方法presentModalViewController:动画:

您的最终代码如下所示:

- (void) viewDidLoad
{
    [super viewDidLoad];

    HomeViewController * homeViewController = [[HomeViewController alloc]initWithNibName:@"HomeViewController" bundle:nil];

    // you can't pass the same view controller to more than one position in UITabBarController
    HomeViewController * homeViewController2 = [[HomeViewController alloc]initWithNibName:@"HomeViewController" bundle:nil];

    // local variable
    self.modalTabBarController = [[UITabBarController alloc] init];

   // Set each tab to show an appropriate view controller
   [self.modalTabBarController setViewControllers:[NSArray arrayWithObjects:homeViewController, homeViewController2, nil]];
}

- (void)viewDidUnload
{
    self.modalTabBarController = nil;
    [super viewDidUnload];
}

 - (IBAction)quickBrowse:(UIButton *)sender
{
    [self presentModalViewController:self.modalTabBarController animated:YES];
}
于 2012-07-22T22:44:29.513 回答