Tuesday, February 16, 2016

Objective C Status Bar color

We may need to change the status bar color based on the app theme color in our application. If our application is having a white theme, default status bar color won't look good. 

Users should have clean status bar when they open our application to check battery, connectivity and all. So it is developer's responsibility to make status bar readable by applying proper color based on app theme color.



                         


Here is the piece of code to customize the status bar theme color for iOS versions greater than 7.0.




   UIView *statusBarDummyView=[[UIView alloc] initWithFrame:CGRectMake(0, 0,
                                [UIScreen mainScreen].bounds.size.width, 20)];                                                      
   [self.window.rootViewController.view addSubview: statusBarDummyView];

   id statusBarWindow = [[UIApplication sharedApplication] 
                                                                   valueForKey:@"statusBarWindow"];

   id statusBar = [statusBarWindow valueForKey:@"statusBar"];

   SEL setForegroundColor_sel = NSSelectorFromString(@"setForegroundColor:");

   if([statusBar respondsToSelector:setForegroundColor_sel])
   {

       [statusBar performSelector:setForegroundColor_sel 
                                                      withObject:[UIColor blueColor]];                                

   }




What we are doing is, taking a view of screen size width and a height of 20 pixels, which is status bar default height and adding it to the window's root view controller's view as subview. After that we are setting the foreground color of the status bar window to our required color, in this case blue color.


Hope this post is useful. Feel free to comment in case of any queries.