我正在使用Storyboard,并且有一个带有五个选项卡的标签栏控制器。在Storyboard中,我可以设置标签栏项目的图像。苹果文档建议为每个选项卡栏项目准备两个图标-一个用于选定状态,另一个用于未选定状态。
我无法弄清楚如何在Storyboard中实现这一点。
是的,这不能使用Storyboard完成 - 需要编写代码。
在 UINavigationViewController
的 viewDidLoad
方法中,我们可以编写以下代码 -
UITabBar *tabBar = self.tabBar;
UITabBarItem *targetTabBarItem = [[tabbar items] objectAtIndex:0]; // whichever tab-item
UIImage *selectedIcon = [UIImage imageNamed:@"name-of-selected-image.png"];
[targetTabBarItem setSelectedImage:selectedIcon];
UINavigationViewController
的类,如果你指的是 UINavigationController
,它没有叫做 tabBar
的属性。 - SteveUITabBar *tabBar = self.navigationController.tabBarController.tabBar;
- CTiPKASWIFT 3.0 --> 设置选项卡按钮图像的理想方式如下:
首先设置您要用于按钮的图像:
let homeImage = UIImage(named: "TabHome")
let homeTappedImage = UIImage(named: "TabHomeRed")
然后设置类型为UITabButtonItem的按钮:
let homeButton = UITabBarItem(title: homeText, image: homeImage, selectedImage: homeTappedImage)
//with this method you set the image when the button is not selected
homeButton.image = homeImage?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
//with this method you set the image when the button is selected
homeButton.selectedImage = homeTappedImage?.withRenderingMode(.alwaysOriginal)
objectAtIndex:0
)。viewDidLoad
方法中: if (self.navigationController.viewControllers.count < 2)
self.navigationController.tabBarItem.selectedImage = [UIImage imageNamed:@"image-selected.png"];
< p > if
条件确保按钮仅在最顶层的视图控制器中更改。当您将视图控制器在导航层次结构中重用为子视图控制器时,这是必需的。
UINavigationController
的根视图控制器。 - Steve
initWithTitle:image:selectedImage:
- T. Benjamin Larsen