There are times when you want to put the original image in the NavigationBar and make it a little richer, right? At that time, if you try to do it in the usual way, it will be displayed in blue.
·ideal
·reality
I would like to keep a memorandum of what I can do to avoid this.
First, try as usual. Is it like this when written in code?
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
}
private func setupNavigationBar() {
navigationItem.title = "Main page"
let button = UIButton(type: .system)
button.setImage(UIImage(named: "button_refresh"), for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
let rightItem = UIBarButtonItem(customView: button)
navigationItem.rightBarButtonItem = rightItem
}
@objc private func buttonAction() {
print("The color of the button is strange! !! !!")
}
Actually, it's faster to add it in Storyboard, but since this is a group that writes in code, I usually do this (Iron's will).
If you write it like this for the time being, the button icon will be filled with blue, which makes you feel sad.
When writing in code, it is OK just to rewrite the place where setImage is set in the button. Specifically, it looks like this.
button.setImage(UIImage(named: "button_refresh")?.withRenderingMode(.alwaysOriginal), for: .normal)
UIImage has Rendering Mode,
automatic | Default. It will select the mode when you use the image. |
alwaysOriginal | Always display the original image |
alwaysTemplate | It depends on the tint color of the button etc. |
You can specify three.
This time, I want to display the original image on the Navigation Bar, so I specified ʻalways Original. On the contrary, if you want to match with tintColor, you can specify ʻalwaysTemplate
.
However, for those of you who find it cumbersome to write in code, there is a direct way to do it in Assets.xcassets. First, open Assets.xcassets, select the desired image, and then
Look at the second Renser As
from the top of the Image Set items on the right. If nothing is specified, it should be Default
.
You already know the rest. If you change the value of Renser As
to ʻOriginal Image, it will automatically become ʻalways Original
without using with Rendering Mode
in your code.
That's why it was the setting method for Rendering Mode of UIImage. Even though it is a function that you use unexpectedly, you may not be able to remember it by accident (4 losses), so please be careful.