swift ios trying to change color of status bar on

2019-07-12 02:26发布

问题:

In my app I have 4 ViewController and in two of them I am changing the status bar from white to black like this:

override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)

        UIApplication.sharedApplication().statusBarStyle = .LightContent
    }

The problem is if I switch between two ViewController that both have the code above the status bar will first change to black which is right, but then it changes to white again when entering the other ViewController.

How can I keep the status bar white on certain ViewController's ?

回答1:

Try to add the following method in your VC's. Use .default or .lightContent to change the status bar color. I tested using Xcode 8 and swift 3:

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return UIStatusBarStyle.default;
}

I created a new tabbed application with Xcode 7.3.1 and swift 2.3. I have two tabs with the classes associated FirstViewController and SecondViewController. In FirstViewController I added the following method:

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return UIStatusBarStyle.Default;
}

And In the SecondViewController, I changed the background to black and I added the following method:

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return UIStatusBarStyle.LightContent;
}

Finally, I added two buttons in the FirstViewController. One button present a controller modally and the other button present through push. When I presented the view modally the 'preferredStatusBarStyle' work but when I presented through push I need to add the following line of code:

self.navigationController?.navigationBar.barStyle = .Black


回答2:

If you really don't want to override the delegate methods for preferredStatusBarStyle, you can still use:

UIApplication.sharedApplication().statusBarStyle = .LightContent

by removing:

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)

    UIApplication.sharedApplication().statusBarStyle = .LightContent
}

and let just let the status bar be set by whats happening in viewWillAppear. Obviously this is more prone to error, but if your navigation is relatively linear then it would be the simplest solution