StartPlayer
StartPlayer

Reputation: 495

changing colour of a Navigation Bar Button

I have a method to change the colour of an image. I use this colour icons in menus of my app quickly without having to go any create and image of the correct colour each time.

/// 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
    }

}

This works fine most of the time. However my problem is trying to set the colour of an image in a navigation bar it doesn't work at all and the image stays its original colour.

I'm trying the following

    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)

I could very easily fix the problem by just making a graphic of the correct colour. However I want to keep these colour changes in app for when a client decides the want to change colours. I'm wondering why I cant get it to work in the nav bar? Is there a fix for this?

Upvotes: 1

Views: 294

Answers (1)

Upholder Of Truth
Upholder Of Truth

Reputation: 4711

There is always a problem accessing a buttons image property of its image view directly like this:

buttom.imageView.image = testImage

You could try this instead which works for me:

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)
    }
}

Using that you pass the button instead of the image view and the function uses the setImage method of UIButton to set it. That appears to get round the problem.

Upvotes: 1

Related Questions