Forum Xamarin.Forms

How to change status bar color in iOS?

stesvisstesvis USMember ✭✭✭✭

I would like to change the status bar background color and text color in iOS to match android.
I found options like this one: MainPage.SetValue(NavigationPage.BarBackgroundColorProperty, Color.Black); but it does not work.

All the other examples suggest to set the BarBackgroundColor and BarTextColor on the navigation page, but that I believe that it would apply to the navigation bar. Instead i need to change the status bar (the bar where you see the battery status, the clock etc.)

Anyone has done it before? Thx

Tagged:

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    The status bar's color will follow the navigation bar's color on iOS so generally, we only manipulate the color of the navigation page's navigation bar.
    But if you want to set it separately you have to use Dependency Service to implement it on iOS project.
    Create an interface like:

    namespace Sample
    {
        public enum BarStyle
        {
            Default,
            Light
        }
        public interface IStatusBarManager
        {
            void ChangeBarTextColor(BarStyle barStyle);
            void ChangeBarBackgroundColor(Color color);
        }
    }
    

    Implement it on iOS:

    [assembly: Dependency(typeof(StatusBarManagerImplement))]
    namespace Sample.iOS
    {
        public class StatusBarManagerImplement : IStatusBarManager
        {
    
            public void ChangeBarBackgroundColor(Color color)
            {
                UIView statusBar = (UIView)UIApplication.SharedApplication.ValueForKey(new NSString("statusBarWindow")).ValueForKey(new NSString("statusBar"));
                statusBar.BackgroundColor = color.ToUIColor();
            }
    
            public void ChangeBarTextColor(BarStyle barStyle)
            {
                if (barStyle == BarStyle.Light)
                {
                    UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.LightContent;
                }
                else
                {
                    UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.Default;
                }
            }
        }
    }
    

    Please notice we have to add a special key in the info.plist to make the changing text color method work:

    <key>UIViewControllerBasedStatusBarAppearance</key>
    <false/>
    

    And the status text color on iOS only has two colors to be chosen(white and black).
    At last, consume this dependency service on Forms:

    DependencyService.Get<IStatusBarManager>().ChangeBarBackgroundColor(Color.Blue);
    DependencyService.Get<IStatusBarManager>().ChangeBarTextColor(BarStyle.Light);
    
Sign In or Register to comment.