如何在iOS 13中的Swift中立即更改状态栏文本颜色 [英] How to change status bar text color immediately in Swift in iOS 13
问题描述
我正在使用Swift 5.1和Xcode 11.1,目前已经完成了暗模式设计.
I'm using Swift 5.1 and Xcode 11.1 and I've currently finished implementing Dark Mode design.
用户使用此代码在设置页面中更改主题样式后,主题会立即更新.
Theme updates immediately after user changes theme style in settings page with this code.
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
appDelegate.changeTheme(themeVal)
// App Delegate File
...
func changeTheme(themeVal: String) {
if #available(iOS 13.0, *) {
switch AppState.appThemeStyle {
case "dark":
window?.overrideUserInterfaceStyle = .dark
break
case "light":
window?.overrideUserInterfaceStyle = .light
break
default:
window?.overrideUserInterfaceStyle = .unspecified
}
}
}
但是问题是我看不到状态栏文本,因为状态栏文本的颜色和视图颜色是相同的.
But the problem is that I can't see status bar text because status bar text color and view color is same.
有人可以建议我一个好的解决方案吗? 谢谢.
Could anyone please suggest me good solution? Thanks.
推荐答案
状态栏颜色不是全局的(默认情况下),如果将其设置为非ViewControllerBased
,则无法再进行更改.因此,您需要像这样在任何视图中更改设置它:
Status bar color is not global (by default) and if you set that to not ViewControllerBased
, you can't change it anymore. So you need to change set it inside any view you need like this:
var statusBarStyle = UIStatusBarStyle.default { didSet { setNeedsStatusBarAppearanceUpdate() } }
override var preferredStatusBarStyle: UIStatusBarStyle { statusBarStyle }
这两个变量可帮助您更改状态栏.请注意,您可以在动画块内调用setNeedsStatusBarAppearanceUpdate
使其具有动画效果.
these two variables help you to change the status bar. Note that you can call setNeedsStatusBarAppearanceUpdate
inside an animation block to make it animatable.
要检测UserInterfaceStyle
何时更改(并相应地更新statusBar颜色),所有视图和viewController均具有委托功能.因此知道:
to detect when UserInterfaceStyle
change (and update statusBar color accordingly), all views and viewControllers have delegate function for that. So knowing that:
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
updateStatusBarColor()
}
}
这是函数:
func updateStatusBarColor() {
switch traitCollection.userInterfaceStyle {
case .unspecified: statusBarStyle = .default
case .light: statusBarStyle = .darkContent
case .dark: statusBarStyle = .lightContent
}
}
请注意:
ParentViewController定义statusBarColor
.因此,如果您使用常规navigationController
或tabBarController
,则使用这些代码为其自定义类就足够了.
Note that:
the ParentViewController defines the statusBarColor
. So if you are using general navigationController
or tabBarController
, A custom class for them with these codes should be enough.
这篇关于如何在iOS 13中的Swift中立即更改状态栏文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!