Change the iOS Status Bar color in Xamarin.Forms
27 Dec 2016Xamarin.Forms is a great way to abstract the local implementation. But, you know, sometimes you need to perform some small adjustments based on the underlying OS. Is this the case of the iOS Status Bar style.
Xamarin.Forms implements, in the NavigationRenderer, a way to automatically set the style (dark/default or light) by checking the Luminosity value of the BarTextColor property. Check the following code:
if (statusBarColorMode == StatusBarTextColorMode.DoNotAdjust || barTextColor.Luminosity <= 0.5)
{
// Use dark text color for status bar
UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.Default;
}
else
{
// Use light text color for status bar
UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.LightContent;
}
For full code, check the NavigationRenderer source on github Xamarin.Forms project.
Now, if in your code you set the BarTextColor to black, then the status bar style will be the Default (dark). Otherwise, the status bar style will be light (white).
So, if we want to set the BarTextColor, in a classic Xamarin.Forms App class constructor, we’ll have something like this:
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage())
{
BarBackgroundColor = Color.FromHex("#043596"),
BarTextColor = Color.White
};
}
But, this is not enough.
In iOS, we have two ways to set the StatusBarStyle:
- at application level
- at view controller level
The default behavior is at view controller level. Since Xamarin.Forms sets the StatusBarStyle at application level, we need to set the related property in the Info.plist. So, open the info.plist file, go in the Source tab and add a new entry with this values:
Name = UIViewControllerBasedStatusBarAppearance
Type – boolean
Value – No
And we have done! Now start the app and check the result:
Nice and simple!