Iphone 从UITabbarItem和情节提要创建UIViewController

Iphone 从UITabbarItem和情节提要创建UIViewController,iphone,ios,objective-c,xcode,uiviewcontroller,Iphone,Ios,Objective C,Xcode,Uiviewcontroller,如果我按下第二个UILabaritem,我试图打开UIViewController 这是我的第一个ViewController代码。如果我按uitabaritem#1(标记1),它将设置Label.text。在#2,我想切换到secondViewController(标记2),它崩溃了。 有人知道为什么吗?第一个断点位于UIStoryboard。。。(故事板称为:Main.Storyboard)。谢谢你的帮助 #import "ViewController.h" #import "secondV

如果我按下第二个UILabaritem,我试图打开UIViewController

这是我的第一个ViewController代码。如果我按uitabaritem#1(标记1),它将设置Label.text。在#2,我想切换到secondViewController(标记2),它崩溃了。 有人知道为什么吗?第一个断点位于UIStoryboard。。。(故事板称为:Main.Storyboard)。谢谢你的帮助

#import "ViewController.h"
#import "secondViewController.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.tabBar.delegate = self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
    switch (item.tag) {
        case 1:        self.testlabel.text =@"test";
            break;
        case 2:
        {  // create the Storyboard object
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        secondViewController *second = [storyboard instantiateViewControllerWithIdentifier:@"secondview"];
        [self.navigationController pushViewController:second animated:YES];
        }         
        break;
        default:         break; }
}
@end

有几件事

  • 如果尚未为
    UITabBarController

  • 除非您想离开
    UITabBarController
    而不推送视图控制器,否则必须手动将视图控制器设置为tabBar项,或在tabBarController中重新设置视图控制器数组

    NSMutableArray*newControllers=[NSMutableArray arrayWithArray:self.tabBarController.viewControllers]

    [newControllers addObject:second]

    [self.tabBarController setViewControllers:newControllers动画:否]

  • 您的
    UITabBarController
    是否在故事板中?在所需选项卡上按住右键单击按钮并将其拖动到控制器上,然后将该控制器设置为选项卡的位置,如果这样做,则可以忽略上面的1和2

  • uitabarcontroller
    并不意味着每个选项卡都有不同的功能,因此让第一个选项卡设置标签,第二个选项卡显示一个
    UIViewController
    ,这是一种糟糕的编码实践,但这与此无关


  • 在所有这些
    UITabBarController
    之后,应用程序可能会崩溃,因为你的
    UINavigationController
    为零,或者你得到一个“SecondView不是值编码兼容错误”或类似的错误,这意味着在情节提要中将属性设置为不再存在的项。因此,在情节提要中,右键单击视图控制器,查看是否看到任何黄色警告标记,如果看到,请单击它们旁边的“X”。

    Hi,感谢您的努力。我没有使用UITabBarController。只需2个UITabBar和2个UITabbarItem。我尝试在不使用故事板中的UITabBarcontroller的情况下执行此操作,因为我希望以后在每个ViewController中都有自定义选项卡栏。使用UITabbarcontroller可以吗?哦,我知道您在做什么,是的,这是可能的,如果您希望每个控制器都有自定义选项卡栏,那么您走对了,您有错误日志吗?这将有助于我理解您设置的C:[UIStoryboard Storyboard with name:@“Main”bundle:nil];这是您的故事板的名称还是应该是[UIStoryboard storyboard with name:@“MainstryBoard”bundle:nil];我想它现在可以工作了,但是有没有一种不用导航控制器就可以做到这一点的方法呢?