在Swift 4中动态更改状态栏颜色 [英] Change status bar color dynamically in Swift 4

查看:442
本文介绍了在Swift 4中动态更改状态栏颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在.lightContent.default之间动态更改状态栏颜色(因为我的背景可以在同一ViewController中更改).

I would like to change the status bar color between .lightContent and .default dynamically (since my background can change in the same ViewController).

我试图为此创建一个函数,如下所示:

I have tried to make a function for this that looks like this:

func changeStatusBar(useDefault: Bool) {
    if useDefault {
        var preferredStatusBarStyle: UIStatusBarStyle {
            return .default
        }
    } else {
        var preferredStatusBarStyle: UIStatusBarStyle {
            return .lightContent
        }
    }
    setNeedsStatusBarAppearanceUpdate()
}

但是没有运气.我在网上(或在Stackoverflow上)找到的每本指南仅显示了一次更改statusBar的方法,而不是通过函数进行的打开和关闭.

But no luck. Every guide i found online (or here on Stackoverflow) only shows how to change the statusBar once, and not on and off through a function.

我还在info.plist文件中将View controller-based status bar appearance设置为NO.

I have also set View controller-based status bar appearance to NO in the info.plist file.

我以前使用的行是UIApplication.shared.statusBarStyle = .lightContent-但由于自iOS9起已弃用该行,所以我不能再使用它.

The line i used to use is UIApplication.shared.statusBarStyle = .lightContent - but since this is deprecated since iOS9, i can't use it anymore.

任何人都知道如何动态更改此内容?

Anyone has some idea how I can change this dynamically?

推荐答案

创建类型为UIStatusBarStyle的属性,并在preferredStatusBarStyle

Create a property with type UIStatusBarStyle and return the value in preferredStatusBarStyle

您可以随时更改其值,并调用setNeedsStatusBarAppearanceUpdate()

And you can change its value whenever you need and call setNeedsStatusBarAppearanceUpdate()

class ViewController: UIViewController {

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return self.style
    }
    var style:UIStatusBarStyle = .default

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func changeStyle(_ sender: UIButton) {
        if self.style == .lightContent {
            self.style = .default
        } else {
            self.style = .lightContent
        }
        setNeedsStatusBarAppearanceUpdate()
    }
}

override var preferredStatusBarStyle: UIStatusBarStyle { return self.style }

如果您将视图控制器嵌入到一个

中,则不会被调用 导航控制器您应该更改导航控制器的栏样式

wont be called if you have embedded your view controller in a navigation controller You should change bar style of your navigation controller

self.navigationController?.navigationBar.barStyle = //newStyle

这篇关于在Swift 4中动态更改状态栏颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆