UITabBar not showing selected item images in ios 7

2020-01-27 00:27发布

The icons show fine in ios 6 but not in ios 7. I'm setting the selected state in the viewController viewDidLoad method. When the user selects a tab bar item the image disappears. Here is my code:

UITabBar *tabBar = self.tabBarController.tabBar;
if ([UITabBar instancesRespondToSelector:@selector(setSelectedImageTintColor:)]) {
    [self.tabBarController.tabBar setSelectedImageTintColor:[UIColor whiteColor]];
}
UITabBarItem *item0 = [tabBar.items objectAtIndex:0];
UITabBarItem *item1 = [tabBar.items objectAtIndex:1];
UITabBarItem *item2 = [tabBar.items objectAtIndex:2];
UITabBarItem *item3 = [tabBar.items objectAtIndex:3];
[item0 setTitle:@"Home"];
[item1 setTitle:@"Calendar"];
[item2 setTitle:@"News"];
[item3 setTitle:@"My Events"];
[item0 setFinishedSelectedImage:[UIImage imageNamed:@"homeIconSelected.png"] withFinishedUnselectedImage:[UIImage imageNamed:@"home2.png"]];
[item1 setFinishedSelectedImage:[UIImage imageNamed:@"Calendar"] withFinishedUnselectedImage:[UIImage imageNamed:@"CalendarIconSelected"]];
[item2 setFinishedSelectedImage:[UIImage imageNamed:@"NewsIconSelected"] withFinishedUnselectedImage:[UIImage imageNamed:@"News"]];
[item3 setFinishedSelectedImage:[UIImage imageNamed:@"EventsIconSelected"] withFinishedUnselectedImage:[UIImage imageNamed:@"Events"]];
[item1 imageInsets];
[item2 imageInsets];
[item3 imageInsets];

20条回答
beautiful°
2楼-- · 2020-01-27 00:54

After trying all of the other answers and struggling as they failed, I found the answer. The other answers, , don't seem to work in current swift version. In Swift 2.3, this works for me. For those who are still having trouble, try this:

tabBarItem.image = UIImage(named: "image_name")
searchVC.tabBarItem.selectedImage = UIImage(named:
     "image_name_when_selected")?.imageWithRenderingMode(.AlwaysOriginal)
查看更多
混吃等死
3楼-- · 2020-01-27 00:56

You need to use tabBarItem initWithTitle:image:selectedImage

[[UITabBarItem alloc] initWithTitle:@"title" image:image selectedImage:imageSel];

in conjunction with changing the UIImage rendering mode:

imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal

or (to apply parent views template tint mask, this option is default for Tab bar Items unless you opt out with the above rendering mode)

imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate

here is a code sample for one tab bar item :-

UIImage *musicImage = [UIImage imageNamed:@"music.png"];
UIImage *musicImageSel = [UIImage imageNamed:@"musicSel.png"];

musicImage = [musicImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
musicImageSel = [musicImageSel imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

self.musicViewController.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Music" image:musicImage selectedImage:musicImageSel];

Hope this helps

查看更多
登录 后发表回答