swift ios trying to change color of status bar on certain VC's

♀尐吖头ヾ 提交于 2019-12-23 22:13:38

问题


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



来源:https://stackoverflow.com/questions/38546787/swift-ios-trying-to-change-color-of-status-bar-on-certain-vcs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!