daniel
daniel

Reputation: 966

How would I create a bar button item that has both title and image in iOS, with the image showing as is without a tint?

I have found solutions on stackoverflow to create a bar button item in iOS that has both title and image, but the image has a blue tint instead of showing as is. I have found solutions on stackoverflow to show the image in a bar button item as is without showing a blue tint, but the bar button item does not show a title.

Is it possible to create a bar button item that has both title and image with the image showing as is?

Here is my code:

let image = UIImage(named: "iMessage Icon 40x30.png")
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 500, height: 30)
button.setTitle("Purchase iMessage Saved Messages", for: .normal)
button.setImage(image, for: .normal)
button.addTarget(self, action: #selector(self.tap), for: .touchUpInside)
button.sizeToFit()
let customBarButtonItem = UIBarButtonItem(customView: button)
navigationItem.leftBarButtonItem = customBarButtonItem

This code creates the bar button item with the image as is, without a blue tint, but the title doesn't show. If I change the second line of code and init the UIButton object as a type system, the title shows as well as the image, but the image has a blue tint, which I don't want.

Upvotes: 0

Views: 63

Answers (2)

kanhaiya choudhary
kanhaiya choudhary

Reputation: 57

I'm Agree with above answer but in my case below code working fine.

button.setImage(UIImage(named: "ImageName.png").withRenderingMode(.automatic), for: UIControl.State.normal)

Upvotes: 1

Mehul Thakkar
Mehul Thakkar

Reputation: 12594

As you already mentioned in question, with type as system, you can see the image and title both.

So, you UIButton of system type, and change the below line from your code

button.setImage(image, for: .normal)

to this one:

button.setImage(image.withRenderingMode(.alwaysOriginal), for: .normal)

This will not allow tint to apply over your image and will use original image.

Upvotes: 1

Related Questions