简体   繁体   中英

How to change the tab bar image color for selected and unselected

I'm trying to change the color of a tab bar item in iOS app.

The child view controllers are embedded in an navigation controller.

I have added this code in AppDelegate which just changes the color of the text.

 [UITabBarItem.appearance setTitleTextAttributes:
 @{NSForegroundColorAttributeName : [UIColor colorWithRed:38/255.0 green:54/255.0 blue:73/255.0 alpha:1.0]}
                                       forState:UIControlStateNormal];

 [UITabBarItem.appearance setTitleTextAttributes:@{NSForegroundColorAttributeName : kColorTabbarNavigationBarTint}
                                       forState:UIControlStateSelected];

And inside the image assets,if I make the particular image to be rendered as original it works, but the selection color does not work for the image.

Please let me know what could be done.

Thanks in advance...

Try below code : When you want to set programatically.

// get your TabBarController
//UITabBarController *tabBarController = self.tabBarController
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController; 
UITabBar *tabBar = tabBarController.tabBar;

UITabBarItem *tabItem1 = [tabBar.items objectAtIndex:0];
[tabItem1 setSelectedImage:[UIImage imageNamed:@"selectimg"]];
tabItem1.selectedImage = [[UIImage imageNamed:@"selectimg"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabItem1.image = [[UIImage imageNamed:@"deselectimg"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabItem1.title = @"xxxx";

UITabBarItem *tabItem2 = [tabBar.items objectAtIndex:1];
tabItem2.selectedImage = [[UIImage imageNamed:@"selectimg"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabItem2.image = [[UIImage imageNamed:@"deselectimg"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabItem2.title = @"xxxx";

UITabBarItem *tabItem3 = [tabBar.items objectAtIndex:2];
tabItem3.selectedImage = [[UIImage imageNamed:@"selectimg"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabItem3.image = [[UIImage imageNamed:@"deselectimg"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabItem3.title = @"xxxx";

UITabBarItem *tabItem4 = [tabBar.items objectAtIndex:3];
tabItem4.selectedImage = [[UIImage imageNamed:@"selectimg"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabItem4.image = [[UIImage imageNamed:@"deselectimg"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabItem4.title = @"xxxx";

Or you can set it in storyboard, Select particular tab item and see below

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM