问题
I am trying to add an icon which is multicolored and when I added the icon as per in the tab bar, it is showing a single color blue, the actual colors of the icon are not visible?
how should I add the colored icon in the tab bar?
回答1:
In assets folder in x-code select your image and in attribute inspector change value of Render As to "Original Image" instead of "Default".
回答2:
Don't do it in the storyboard. Try this:
extension UITabBarItem {
convenience init(title: String, unselected: String, selected: String) {
let selectedImage = UIImage(named: selected)?.withRenderingMode(.alwaysOriginal)
let unselectedImage = UIImage(named: unselected)?.withRenderingMode(.alwaysOriginal)
self.init(title: title, image: unselectedImage, selectedImage: selectedImage)
}
}
and then in viewDidLoad
in your view controller...
tabBarItem = UITabBarItem(title: "My title",
unselected: "unselectedIconName",
selected: "selectedIconName")
回答3:
This is because in a tab bar all images are displayed with rendering mode set to template
, you can override this behavior forcing rendering mode when loading the image:
let yourImage = UIImage(named: "your_image")?.withRenderingMode(.alwaysOriginal)
and then use your image as a tab bar icon.
回答4:
It is better do this in code like this:
var aViewController: UIViewController = UIViewController()
// This statement is what you need
var myTabBarItem: UITabBarItem = UITabBarItem(title: nil, image: UIImage(named: "YOUR_IMAGE_NAME")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), selectedImage: UIImage(named: "YOUR_IMAGE_NAME"))
aViewController.tabBarItem = myTabBarItem
来源:https://stackoverflow.com/questions/58726083/how-to-add-colored-icon-in-ios-swift