jazzedge
12/23/2017 - 8:29 AM

Swift - Coloured Status Bar

The status bar is an odd creature. Views that scroll up beyond the top 'safe area' of the screen show underneath the status bar.
This can look pretty ugly. At the same time, if your VC is embedded in a navigation controller, then the VC flows behind the top navigation bar and then shows up on the status bar. Again, unsightly.
Navigation bars embedded through Navigation controllers do NOT scroll up when your view does.
Navigation bars that you drag onto the view, instead DO scroll up when your view does.
Finally, it is quite hard to set the colour of the status bar background and text, changing depending on whether your VC is embedded in a Nav Controller or not.

So:

1. Add this to AppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        // This is required to remove the fuzzy pale overlay on nav bar of the UITableViewController, which makes the underlying color insipid.
        // It is used here because you can't reference the nav bar of the UITableViewController.
        // It is not needed for regular UIViewControllers with a drag-and-drop navigation bar
        UINavigationBar.appearance().backgroundColor = Constants.cFoundationColor
        UINavigationBar.appearance().isTranslucent = false
        UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
        
        return true
    }
    
2. Add just this in viewDidLoad for VCs embedded in NCs to change the color of the status bar text
    
        // This makes the status bar text white
        UIApplication.shared.statusBarStyle = .lightContent
        
3. Add this instead of (2) above, for VCs NOT embedded in NCs. As well as changing the color of the status bar text, it sets the colour of the nav bar placed manually.

    func presentTransparentNavigationBar() {
        userProfileNavigationBar.setBackgroundImage(UIImage(), for:UIBarMetrics.default)
        userProfileNavigationBar.isTranslucent = true
        userProfileNavigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
        userProfileNavigationBar.shadowImage = UIImage()
        
        // This makes the status bar text white
        UIApplication.shared.statusBarStyle = .lightContent
    }
    
4. then, if you use (3) call presentTransparentNavigationBar from viewDidLoad