在Button按下访问TabBarController

时间:2012-07-22 20:54:00

标签: iphone objective-c ios ios4 uitabbarcontroller

我已经以编程方式创建了一个带有视图等的TabBarController。现在我想在Button Press上显示这个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];
}

1 个答案:

答案 0 :(得分:1)

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

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

您的最终代码如下所示:

- (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];
}