【问题标题】:How to add a Tab Bar to an existing view controller, without XIB如何在没有 XIB 的情况下将选项卡栏添加到现有视图控制器
【发布时间】:2010-03-22 13:40:33
【问题描述】:

尽量避免使用 Interface Builder

目前我已经通过代码创建了视图控制器,并通过代码更改了视图。

我现在需要一个步骤来将应用程序发送到带有标签栏的新视图,这也将允许我更改视图。

理想情况下,我会告诉当前视图控制器在底部添加一个 Tab Bar,但我不确定这是否可行,所以我可能不得不将 UIViewController 与 UITabBarController 交换?

我们将不胜感激。

干杯, 安德烈

【问题讨论】:

    标签: iphone xcode uitabbarcontroller


    【解决方案1】:

    我手头没有 Xcode,所以我会尝试口头回答。

    创建一个新的UITabBarController 并将您的当前视图设置为root view,然后根据需要添加尽可能多的选项卡(每个选项卡都有自己的视图)。

    更新
    初始化控制器后,定义一个视图数组(添加顺序很重要)。并在标签栏控制器上调用它

    - (void)setViewControllers:(NSArray *)viewControllers animated:(BOOL)animated
    

    更新 2

    这是一个简单的代码,用于创建一个带有两个空视图的标签栏,每个视图都有自己的标签按钮。

    tabBarController = [[UITabBarController alloc]init];
    
    firstView = [[FirstView alloc] init];
    UITabBarItem *item1 = [[[UITabBarItem alloc]initWithTitle:@"First" image:nil tag:1] autorelease];
    [firstView setTabBarItem:item1];
    
    secondView = [[SecondView alloc] init];
    UITabBarItem *item2 = [[[UITabBarItem alloc]initWithTitle:@"Sec" image:nil tag:1] autorelease];
    [secondView setTabBarItem:item2];
    
    [tabBarController setViewControllers:[NSArray arrayWithObjects:firstView,secondView,nil] animated:NO];
    
    [window addSubview:tabBarController.view];
    

    当然,这段代码没有用,您需要手动创建视图,或者为每个视图创建一个 nib 文件并将其加载到initWithNibName

    更新 3
    查看Stanford iPhone Course,这是斯坦福大学的免费课程。讲师是 Apple 员工。标题为 导航和标签栏控制器 的第 7 课将为您提供有关这些组件的良好开端。

    【讨论】:

    • 谢谢 :) 我已将它添加到视图中,它正在出现,底部有一个空白画布和一个空栏。现在我想弄清楚如何告诉标签栏在白色画布上显示一个特定的视图,以及如何在底部的空标签栏上添加 4 个按钮。
    • 我已将我的特定视图添加到白色画布上。我正在使用:tabBarController = [[UITabBarController alloc] init]; [tabBarController setViewControllers: [NSArray arrayWithObjects: viewController, nil]]; viewController.view = step3;其中“step3”是我想要展示的视图。现在我只是尝试添加实际的选项卡按钮并关联操作以更改视图
    • 对,我已经把按钮放进去了。知道如何让每个按钮调用一个函数来改变视图吗? :) 干杯
    • 我使用以下方法添加了按钮: UINavigationController *tab = [[UINavigationController alloc] initWithRootViewController:viewController];将其推入一个数组,然后使用该数组设置 tabBarController.viewControllers。问题是它会自动在顶部添加一个导航栏。是因为我使用 UINavigationController 为标签栏创建按钮吗?我怎样才能操纵这个导航栏?使用“tabBarController.navigationController.navigationBar”不起作用:(
    • 终于找到了那个。现在只需要将按钮链接到操作 :) 有什么想法吗?
    猜你喜欢
    • 2012-08-22
    • 2013-04-24
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    相关资源
    最近更新 更多