0

I am trying to hide the status bar when the user taps a button in a non-UIViewController class, but having no success.

I am using the following code to present the UIAlertController:

public extension UIAlertController
{
    func show()
    {
        let win = UIWindow(frame: UIScreen.main.bounds)
        let vc = UIViewController()
        vc.view.backgroundColor = .clear
        win.rootViewController = vc
        win.windowLevel = UIWindowLevelAlert + 1
        win.makeKeyAndVisible()    
        vc.present(self, animated: true, completion: nil)
    }
}

It was referenced from the following answer by jazzgil:

ios - present UIAlertController on top of everything regardless of the view hierarchy

In my UIButton action I implemented the following:

@IBAction func setImage(_ sender: UIBarButtonItem)
{
    let alertView = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.alert)

    // Create the alert's action button
    let okAction = UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction!) in



    })

    let cancelAction = UIAlertAction(title: "CANCEL", style: .destructive, handler: nil)

    alertView.addAction(okAction)
    alertView.addAction(cancelAction)

    alertView.show()
}

I have tried to add the following function within the extension:

override open var prefersStatusBarHidden: Bool
{
    return true
}

Then set alertView.modalPresentationCapturesStatusBarAppearance = true as well as alertView.setNeedsStatusBarAppearanceUpdate() but the status bar always seems to appear.

Can someone guide me in the right direction?

Thanks!

Pangu
  • 3,721
  • 11
  • 53
  • 120

1 Answers1

1

Hope this help you.

To hide status bar call this method(in your case before presenting alertview controller)

func hideStatusBar() {
     UIApplication.shared.keyWindow?.windowLevel = UIWindowLevelStatusBar
}

And to get back status bar call this method(after dismissing alertview controller)

func updateStatusBarToPreviousState() {
     UIApplication.shared.keyWindow?.windowLevel = UIWindowLevelNormal
 }
Sunil Sharma
  • 2,653
  • 1
  • 25
  • 36
  • please explain answer and how to use – Pangu Jul 16 '17 at 18:24
  • Simply you have to call method `hideStatusBar` to hide status bar and to show back call method `updateStatusBarToPreviousState` after dismissing alertview controller. – Sunil Sharma Jul 16 '17 at 18:37
  • `hideStatusBar` works but when I call `updateStatusBarToPreviousState` in my okAction, the status bar never re-appears?? – Pangu Jul 16 '17 at 18:41