Runar Ovesen Hjerpbakk

Programmer. Software Architect. Technical Manager.

Changing the color of buttons in the iOS UINavigationBar

While creating a Xamarin Forms workshop for some local CS students, I encountered what I think to be a bug but might turn out to be a feature.

Consider the following code from AppDelegate.cs:

public override bool FinishedLaunching(
    UIApplication application, NSDictionary launchOptions)
{
    UIButton.Appearance.TintColor = UIColor.Green;
    UINavigationBar.Appearance.TintColor = UIColor.Red;
    return true;
}

What color will a button in the navigation bar have now, green or red?

Before iOS 11, the answer was red. Now it is:

Not what I wanted, but according to Apple, this is by design. Luckily, an easy solution exists.

UIKit is very flexible. Views can have different appearance properties based on which parent they are contained in. To change the color of the buttons in the UINavigationBar, simple use:

public override bool FinishedLaunching(
    UIApplication application, NSDictionary launchOptions)
{
    UIButton.AppearanceWhenContainedIn(typeof(UINavigationBar)).TintColor =
        UIColor.Red;
    return true;
}

I’ve created a simple sample project to illustrate the feature.