Ricardo Guerrero
Ricardo Guerrero

Reputation: 503

How to set a Custom image programmatically to and UIBarButtonItem

I am having a problem assigning a custom image to an UIBarButtonItem, the main problem is that the image appears as an white square when create the button. here is my code:

fileprivate func configureNavigationBar() {
        tabBarController?.navigationItem.title = lot.name
        let exportImg: UIImage = UIImage(named: "action.png")!
        let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(showCreationView(_:)))
        let exportByEmail = UIBarButtonItem(image: exportImg, style: .done, target: self, action: #selector(exportDataByEmail(_:)))
        tabBarController?.navigationItem.rightBarButtonItems = [exportByEmail,addButton]
    }

The problem is with the exportByEmail, image is in the variable exportImg added from my assets:

image1

The result obtained from my code: image2

Upvotes: 0

Views: 87

Answers (1)

Yervand Saribekyan
Yervand Saribekyan

Reputation: 502

Your image's background must be transparent, and you can set always original rendering mode to image, to display without changes as following

let exportByEmail = UIBarButtonItem(image: exportImg.withRenderingMode(.alwaysOriginal), style: .done, target: self, action: #selector(exportDataByEmail(_:)))

Upvotes: 1

Related Questions