【问题标题】:How to create CustomTabBarController using XIB?如何使用 XIB 创建 CustomTabBarController?
【发布时间】:2012-11-04 19:59:01
【问题描述】:

我使用的是 iOS 5.1,我需要为我的应用创建一个自定义 TabBar。当应用程序启动时,控件将被推送到自定义 TabbBar 控制器类。这就是我正在做的事情。 我创建了从 UITabBarController 派生的类,并且我也使用了 XIB。在 XIB 中,我可以看到包含 Tab Bar 的 UIView Objetc,当我在该 tabBar 中添加更多 Tabs 时,当我运行应用程序时它没有反映,我只能看到一个没有任何标题和颜色的黑色 TabBar。 我记得之前我们使用 MainWindow.xib 添加 TabBarController 并为每个 TabBar 项添加导航控制器,以便每个选项卡都有自己的导航控制器,但如果我使用了 XIB,我不知道如何完成派生自 UiTabBarController 类。如果我不清楚,请告诉我。我将给出更多说明。我只想知道为什么XIB的TabBar上的更改没有反映在应用程序中?

下图显示了 XIB 和 App,因此您可以看到我在 UITabBar 中添加了四个选项卡,但在应用程序中只有一个黑条。

【问题讨论】:

    标签: ios customization uitabbar


    【解决方案1】:

    来自关于 UITabBarController 的 Apple 文档: 这个类不用于子类化。相反,您按原样使用它的实例来呈现一个允许用户在不同操作模式之间进行选择的界面

    你不能继承它。如果原来的 UITabBarController 没有你想要的功能,你唯一的选择是创建一个新的自定义标签栏控制器而不继承原来的。

    编辑:不确定是否要这样做。您只是想从笔尖加载 UITabBarController 吗?如果是这样,则不需要子类化。使用故事板会更好;-) 但即使使用笔尖也可以做到。 您只需这样做:

    1-在项目中添加一个空的xib并命名为TabBar(只有xib。没有源文件)

    2- 在该笔尖内放置一个 UITabBarController。没有其他组件,只有那个 UITabBarController

    3- 将此代码放入 AppDelegate 应用程序的 didFinishLaunchingWithOptions 方法中:

    // this code should be already in that method if you have used the empty application model
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    // this is the new code to add. You are programmatically loading an instance of UITabBarController from the nib named TabBar.xib
    UITabBarController *tb = (UITabBarController *)[[[NSBundle mainBundle]loadNibNamed:@"TabBar" owner:self options:nil] objectAtIndex:0];
    // here you are assigning the tb as the root viewcontroller
    self.window.rootViewController = tb;
    
    // this code is standard in this method
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
    

    然后您可以自定义您的 UITabBarController 并且它应该正确加载。 注意:如果在 nib 内添加其他对象,则必须更改行

    UITabBarController *tb = (UITabBarController *)[[[NSBundle mainBundle]loadNibNamed:@"TabBar" owner:self options:nil] objectAtIndex:0];
    

    使用循环和一些检查来查看您是否真的在加载 UITabBarController 而不是其他组件。现在我只是在 nib 中加载第一个对象,而不关心它是 UITabBarController 还是 UIPotato ;-)

    【讨论】:

    • 你的意思是我不能创建从 UITabBarController 派生的类?
    • 不确定您的意思是“派生”。 “你不能子类化”的意思是你不能像这样创建一个类:@interface MyTabBarController : UITabBarController
    • 不,我们可以做到这一点,我之前做过很多次,但我从来没有为此目的使用过 XIB!
    • 你做了并且工作的事实并不意味着:1-受支持(如文档所说,不,不支持)2-它将在未来的iOS版本中继续工作.最近(iOS 6)Apple 做了很多工作来完全避免这种自定义(例如,在 iOS 6 上你不能横向旋转 UIImagePickerController,即使在 iOS 5 上是可能的,因为 Apple 添加了一些安全技巧)。我的消息来源是 Apple 员工 ;-)
    • 好的,iOS 6 可能无法实现,但你能告诉我我的问题的解决方案吗,那就是如何自定义支持 iOS 5 和 iOS 6 的 UITabBar。请询问你的 Apple员工发给我一些示例代码!
    猜你喜欢
    • 2011-01-05
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多