Swift 更改导航栏按钮的颜色
我有一种改变图像颜色的方法。我在我的应用程序的菜单中快速使用这种颜色图标,而不必每次都创建正确颜色的图像Swift 更改导航栏按钮的颜色,swift,uiimageview,uibarbuttonitem,Swift,Uiimageview,Uibarbuttonitem,我有一种改变图像颜色的方法。我在我的应用程序的菜单中快速使用这种颜色图标,而不必每次都创建正确颜色的图像 /// 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
/// 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)
我可以很容易地解决这个问题,只要制作一个正确颜色的图形。不过,我想在应用程序中保留这些颜色变化,以备客户决定更改颜色时使用。我想知道为什么我不能让它在导航栏工作?有解决方法吗?直接访问其图像视图的按钮图像属性时总是会出现问题,如下所示:
buttom.imageView.image = testImage
你可以试试这个,这对我很有用:
func tint(icon image: UIImage, for button: UIButton, with colour: UIColor?) {
if colour != nil {
let template = image.withRenderingMode(.alwaysTemplate)
button.setImage(template, for: .normal)
button.imageView!.tintColor = .red
} else {
button.setImage(image, for: .normal)
}
}
使用它可以传递按钮而不是图像视图,函数使用UIButton的setImage方法进行设置。这似乎解决了问题。非常感谢。我没想到会这样做。我只是需要改变一下。红色变成了颜色,它的工作方式和我想要的完全一样。对不起,是的,我复制了一些硬编码的测试代码,并把它放在那里了。很高兴它能起作用。