Search code examples
iosswiftuinavigationbarios11uistatusbar

How to change UIStatusBarStyle from .lightContent to .default after scrolling starts in a table view?


I am trying to change the preferredStatusBarStyle of a table view controller from .lightContent to .default when scrolling starts? Here is the initial state : enter image description here

And this is the final state : enter image description here I am relatively new to iOS development. Please provide details on how to achieve this?

Thank you!


Solution

  • I found out the solution after scouting for a while....

    If you want to change the status bar style any time after the view has appeared you can use this:

    In file info.list add row: View controller-based status bar appearance and set it to YES

    var viewIsDark = Bool()
    
    func makeViewDark() {
    
    viewIsDark = true
    setNeedsStatusBarAppearanceUpdate()
    }
    
    func makeViewLight() {
    
    viewIsDark = false
    setNeedsStatusBarAppearanceUpdate()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
    
    if viewIsDark {
        return .lightContent 
    } else {
        return .default 
    } 
    }
    

    The above code works if your view controller isn't embedded in a Navigation Controller. If it is embedded in a Navigation Controller, add this to the bottom of the view controller :

     extension UINavigationController
    {
        override open var preferredStatusBarStyle: UIStatusBarStyle {
     // code goes here
         }
     }