在 UINavigationController 中自定义 UITabBarItem

Posted

技术标签:

【中文标题】在 UINavigationController 中自定义 UITabBarItem【英文标题】:Customize UITabBarItem in UINavigationController 【发布时间】:2014-05-13 14:37:05 【问题描述】:

如何更改 UITabBarItem 的背景颜色?我需要这样的东西:

(钱包下的颜色)

【问题讨论】:

【参考方案1】:

添加图片

    UITabBarController *tabController = (UITabBarController *)self.window.rootViewController;

    //tab1
    UIImage *selectedImage = [UIImage imageNamed:@"home-tab-selected"];
    UIImage *unselectedImage = [UIImage imageNamed:@"home2-tab"];
    MyTabBar *tabBar = (MyTabBar *)tabController.tabBar;
    UITabBarItem *item1 = [tabBar.items objectAtIndex:0];
    [item1 setFinishedSelectedImage:selectedImage withFinishedUnselectedImage:unselectedImage];

    //tab2
    selectedImage = [UIImage imageNamed:@"customers-tab-selected"];
    unselectedImage = [UIImage imageNamed:@"customers-tab"];
    UITabBarItem *item2 = [tabBar.items objectAtIndex:1];
    [item2 setFinishedSelectedImage:selectedImage withFinishedUnselectedImage:unselectedImage];

    //tab3
    selectedImage = [UIImage imageNamed:@"maps-tab-selected"];
    unselectedImage = [UIImage imageNamed:@"maps-tab"];
    UITabBarItem *item3 = [tabBar.items objectAtIndex:2];
    [item3 setFinishedSelectedImage:selectedImage withFinishedUnselectedImage:unselectedImage];

    //tab4
    selectedImage = [UIImage imageNamed:@"reports-tab-selected"];
    unselectedImage = [UIImage imageNamed:@"reports-tab"];
    UITabBarItem *item4 = [tabBar.items objectAtIndex:3];
    [item4 setFinishedSelectedImage:selectedImage withFinishedUnselectedImage:unselectedImage];

    //tab5
    selectedImage = [UIImage imageNamed:@"orders-tab-selected"];
    unselectedImage = [UIImage imageNamed:@"orders-tab"];
    UITabBarItem *item5 = [tabBar.items objectAtIndex:4];
    [item5 setFinishedSelectedImage:selectedImage withFinishedUnselectedImage:unselectedImage];


    if ([tabBar respondsToSelector:@selector(setBackgroundImage:)])
    
        // ios 5 code here
        [tabBar setBackgroundImage:[UIImage imageNamed:@"tab-bg"]];

      

【讨论】:

【参考方案2】:

看看UITabbarItem的外观代理,特别是-selectedImage(doc)方法。 请注意,在 iOS7 中,大多数图像都呈现为模板(我不知道在标签栏项目中),因此您应该指定它们的呈现模式。 类似的东西:

[[UIImage imageNamed:@"wallet"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

这些方法在 iOS7 上是安全的,如果您需要在较低的目标上部署,最好检查它们是否可用,否则您的应用会崩溃。

【讨论】:

以上是关于在 UINavigationController 中自定义 UITabBarItem的主要内容,如果未能解决你的问题,请参考以下文章

在 UINavigationController 内的 UITabBarcontroller 中添加 UINavigationController?

从嵌入在 UINavigationController 中的一个视图控制器到另一个 UINavigationController

(Swift) 在嵌套在 Main UINavigationController 中的 UINavigationController 和 UITabController 之间切换

关闭 UINavigationController 并呈现另一个 UINavigationController

带有主 UINavigationController 和详细 UINavigationController 的 UISplitViewcontroller

UINavigationController 标题和按钮