我有一种改变图像颜色的方法。我在我的应用程序的菜单中快速使用这种颜色图标,而无需每次都创建正确颜色的图像。
/// Tint an image with a selected colour.
///
/// - Parameters:
/// - image: The image you wish to colour
/// - imageView: The imageView containing the image
/// - colour: Colour you wish to tint image with. Set as nil if you dont want to change it or im image is multicoloured.
func tint(icon image:UIImage, for imageView:UIImageView, with colour:UIColor?) {
if colour != nil {
let template = image.withRenderingMode(.alwaysTemplate)
imageView.tintColor = colour!
imageView.image = template
} else {
imageView.image = image
}
}
这在大多数情况下都很有效。然而,我的问题是试图在导航栏中设置图像的颜色,它根本不起作用,图像保持其原始颜色。
我正在尝试以下方法
let dashboardButton = UIButton(type: .custom)
let dashboardButtonImage = UIImage(named: "example image name")
dashboardButton.setImage(dashboardButtonImage.imageResize(sizeChange: CGSize(width: 20, height: 20)), for: .normal)
style.tint(icon: dashboardButtonImage, for: dashboardButton.imageView!, with: .red)
dashboardButton.contentHorizontalAlignment = .fill
dashboardButton.contentVerticalAlignment = .fill
dashboardButton.imageView?.contentMode = .scaleAspectFit
dashboardButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
dashboardButton.addTarget(self, action: #selector(ExampleViewController.goToDashboard), for: .touchUpInside)
let dashboardItem = UIBarButtonItem(customView: dashboardButton)
self.navigationItem.setRightBarButtonItems([dashboardItem], animated: false)
我可以很容易地解决这个问题,只需制作一个正确颜色的图形。然而,我想在应用程序中保留这些颜色变化,以备客户决定更改颜色时使用。我想知道为什么我不能让它在导航栏工作?有解决方法吗?