Changing colors of UINavigationBarButtons : SkyBlog.

Alright, here’s another quick tip. “How to change the colors of a button on a toolbar.” Of course, this can be applied to any toolbar but I am going to demonstrate the procedure on a UINavigationBar.

The above image only shows a couple of colors. In truth, you can make the button any color that you want. Fantastic! The code is really simple to do this as well. The first thing that we want to do is open the header file for whichever object will be turning a nav bar button a different color and declare the forward class UINavigationButton. You can get this class by either iterating through the subviews of the UINavigationBar, reading its subviews class names, or by class-dumping UIKit if you have a jailbroken device.

Place the following line before your interface declaration:

Now, declare a new method in the header that we will use to actually change the button’s color.

Or something similar to the above line of code.

Now, open up your object’s implementation file and implement the above method. Anywhere in your file, add the following method:

As you can see above, this is actually a lot easier than it first appears to be. What we first do is set up a for loop to iterate through the subviews of the UINavigationBar using NSFastEnumeration. We then output the class name of the subview, for future reference. IF the class name is UINavigationButton, then we’ve got our view. All we do is set the tintColor property if the UINavigationButton.

That’s it, we’re done!

Alternatively, if you want a wider scope, I’d suggest creating a new UINavigationBar category and placing the button color changing method in there. This was your method can be performed by any class that uses a UINavigationBar without having to recreate the same method over and over.

Remember, a back button and a navigation button are not the same thing. You will have to color the back button separately.

And as usual, here’s a link to a sample app that demonstrates this code:

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注