how to add colored icon in ios swift?

可紊 提交于 2020-01-16 09:05:06

问题


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

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