Search code examples
iosswiftuistatusbar

Animate UIStatusBar ios9+ (swift)


I'm trying to animate the status bar based on the scroll direction of my scroll view. Currently, I am able to hide the status bar, however I can't get the change to animate.

I thought there was a method that did handled this, considering one exists for the navigation bar, and I found the method setStatusBarHidden(_:with:), however this method appears to have been deprecated since ios9.

Right I am setting the status in an animation block and calling .setNeedsStatusBarAppearanceUpdate() as seen below

DispatchQueue.main.async {
            UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
                UIApplication.shared.isStatusBarHidden = true
                self.setNeedsStatusBarAppearanceUpdate()
            }, completion: { (completed) in
            })
        }

One other thing, is it still possible to set the animation style? Before, using the setStatusBarHidden method, you could choose between a couple different animation styles (fade and slide).


Solution

  • What you're doing was never right. You should not be talking to the shared application. It is the top-level view controller that is in charge of the status bar visibility, through the value of its prefersStatusBarHidden property.

    The following snippet demonstrates how the top-level view controller can toggle status bar visibility with animation (in response to the tapping of a button, for demonstration purposes):

    var hide = false
    override var prefersStatusBarHidden : Bool {
        return self.hide
    }
    @IBAction func doButton(_ sender: Any) {
        self.hide = !self.hide
        UIView.animate(withDuration:0.4) {
            self.setNeedsStatusBarAppearanceUpdate()
            self.view.layoutIfNeeded()
        }
    }
    

    The same is true of .fade and .slide; these are to be given as the value of the top level view controller's override of the preferredStatusBarUpdateAnimation property.