Change Default “Not Selected” UITabBarItem Image Color

霸气de小男生 提交于 2019-12-11 03:55:16

问题


how do we change the "Not Selected" or the unhiglighted state of the icons in UITabBarItem?

I tried setting the UITabBarItem.appearance().setTitleTextAttributes(:) but it only changes the text color.

Any idea?


回答1:


If you want to change the default in iOS 7 and above, you have to actually use different icons (in the color you like to have for unselected tabs) and set the color of the text. Instead of creating two sets of icons, you could apply this tweak:

// set the selected colors
[self.tabBar setTintColor:[UIColor whiteColor]];
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor], NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];


UIColor * unselectedColor = [UIColor colorWithRed:184/255.0f green:224/255.0f blue:242/255.0f alpha:1.0f];

// set color of unselected text
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:unselectedColor, NSForegroundColorAttributeName, nil]
                                     forState:UIControlStateNormal];

// generate a tinted unselected image based on image passed via the storyboard
for(UITabBarItem *item in self.tabBar.items) {
   // use the UIImage category code for the imageWithColor: method
   item.image = [[item.selectedImage imageWithColor:unselectedColor] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

Source.




回答2:


It can be done using 'xcode' alone. Add two duplicate sets of 'images' to 'Assets.xcassets'. Name the second set of images differently, for example, name them 'yourNameSelected'. Set 'Render As Original Image' property for first (unselected) set of icons:

Set these images for unselected position:

Set the 'yourNameSelected' duplicate images as Selected Image, then go to the Tab Bar Attributes inspector and select Image Tint you need for the selected tabs color.

If you target is below ios10, you need to import colored images for two states and render both as original image.




回答3:


In swift tab bar item icons presented by its own image like that, so you can apply your own presets

var myImage = UIImage(named: "someImageName")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
myImageView.tintColor = UIColor.redColor()
myImageView.image = myImage


来源:https://stackoverflow.com/questions/30664500/change-default-not-selected-uitabbaritem-image-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!