gpt4 book ai didi

ios - 如何在 iOS 13 的 Swift 中立即更改状态栏文本颜色

转载 作者:行者123 更新时间:2023-11-28 11:24:39 25 4
gpt4 key购买 nike

我正在使用 Swift 5.1 和 Xcode 11.1,目前我已经完成了深色模式设计的实现。

用户使用此代码在设置页面中更改主题样式后,主题会立即更新。

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
}
}
}

但问题是我看不到状态栏文本,因为状态栏文本颜色和 View 颜色相同。

谁能给我建议好的解决方案?谢谢。

最佳答案

状态栏颜色不是全局的(默认情况下),如果您将其设置为非 ViewControllerBased,您将无法再更改它。所以你需要像这样在你需要的任何 View 中更改设置它:

var statusBarStyle = UIStatusBarStyle.default { didSet { setNeedsStatusBarAppearanceUpdate() } }
override var preferredStatusBarStyle: UIStatusBarStyle { statusBarStyle }

这两个变量帮助你改变状态栏。请注意,您可以在动画 block 内调用 setNeedsStatusBarAppearanceUpdate 以使其可动画化。

为了检测 UserInterfaceStyle 何时更改(并相应地更新 statusBar 颜色),所有 View 和 viewController 都具有相应的委托(delegate)函数。所以知道:

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。因此,如果您使用的是通用 navigationControllertabBarController,使用这些代码为它们定制一个类就足够了。

关于ios - 如何在 iOS 13 的 Swift 中立即更改状态栏文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58589634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com