【iOS】tabBarItem图标颜色无效

码出境界 / 2024-08-23 / 原文

UI给的图是有颜色的,并且给了selected和unSelected两种状态的图片,但是如果通过下面方式赋值图片,会发现,最后的效果没有使用UI设定的颜色,而是未选中就是灰色,选中了就是蓝色:

UITabBarItem *tabBarItem = [[UITabBarItem alloc] initWithTitle:LS(@"About") image:[UIImage imageNamed:@"tab_icon_about_active"] tag:4];
[self setTabBarItem:tabBarItem];

在 iOS 开发中,UITabBarItem 的图标通常会被渲染成蓝色,这个颜色取决于应用的主题颜色或者系统的默认颜色。

使用 Objective-C 来设置 UITabBarItem 的图标颜色为原始颜色,可以按照以下代码来实现:

// 设置未选中的图标
UIImage *normalImage = [[UIImage imageNamed:@"yourImageName"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
tabBarItem.image = normalImage;

// 设置选中时的图标
UIImage *selectedImage = [[UIImage imageNamed:@"yourSelectedImageName"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
tabBarItem.selectedImage = selectedImage;

要修改 UITabBarItem 的模板颜色(也就是未选中时的图标颜色),你可以通过设置 UITabBarunselectedItemTintColor 属性来实现。以下是使用 Objective-C 的代码示例:

// 设置选中状态下的图标颜色
tabBarController.tabBar.tintColor = [UIColor selectedColor];

// 设置未选中状态下的图标颜色
tabBarController.tabBar.unselectedItemTintColor = [UIColor unselectedColor];