Search code examples
swiftuiimageuinavigationbaruinavigationitem

Change UINavigationBar button image


I am trying to replace the image displayed in my right navigation bar button when it is tapped.

At the moment what seems to be happening is that it is not replacing the button, but trying to set it while the old one still exists. This leads to a strange effect as you can see:

enter image description here

It's a compass image, so there should only be one circle, but as you can see three are appearing.

This is my code:

let backImg: UIImage = UIImage(named: "Compass.png")!
navButton.setBackgroundImage(backImg, forState: .Normal, barMetrics: .Default)

Is there a way to remove the existing one and replace it with the new one?

Thanks.


Solution

  • It sounds like perhaps you are setting the UIBarButtonItem's backgroundImage when what you really want to set is its image. Thus you end up seeing both of them.