Search code examples
swiftxcodehidestatusbar

How to hide status bar in swift 5?


When I scroll, navigation bar and Status Bar hide And it works well But when I go to another page and go back to the first page, navigation bar goes into hiding, but the status bar will not be hidden again. i want to hide status bar when i scroll . such as navigation bar

this is my code :

class ViewController: UIViewController {
@IBOutlet weak var View_Mor: UIView!
override func viewDidLoad() {
    super.viewDidLoad()
    navigationController?.hidesBarsOnSwipe = true
}
override var prefersStatusBarHidden : Bool {
    if self.navigationController?.isNavigationBarHidden == true {
        return true
    } else {
        return false
    }
}

}

@IBAction func gotosecondvc(_ sender: UIBarButtonItem) {
    let st = UIStoryboard(name: "Main", bundle: nil)
    let vc = st.instantiateViewController(withIdentifier: "secondvc")
    vc.modalPresentationStyle = .overFullScreen
    present(vc,animated: true,completion: nil)
    }

Solution

  • What you can do is implement this function.

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
        if scrollView.isTracking {   
        // ... perform actions
             //MARK:- Show Status Bar
             UIApplication.shared.isStatusBarHidden = true
        } else {
        //.. not tracking
            //MARK:- Hide Status Bar
            UIApplication.shared.isStatusBarHidden = false
        }
    }
    

    you can then detect when the user is dragging the scroll view and perform actions based on what it is you want to do and when.

    I hope this helps.

    Edit———-

    private var hideStatusBar: Bool = false
    
    override var prefersStatusBarHidden: Bool {
        return hideStatusBar
    }
    
    override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
        return UIStatusBarAnimation.slide
    }
    

    Usage

       func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
            if scrollView.isTracking {   
            // ... perform actions
                 hideStatusBar = true 
            } else {
            //.. not tracking
                hideStatusBar = false 
            }
        }