3

我正在使用 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
       }
   }
}

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

谁能给我一个好的解决方案?谢谢。

4

1 回答 1

7

状态栏颜色不是全局的(默认情况下),如果您将其设置为 not ViewControllerBased,您将无法再更改它。因此,您需要在所需的任何视图中更改设置,如下所示:

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

这两个变量可帮助您更改状态栏。请注意,您可以setNeedsStatusBarAppearanceUpdate在动画块内部调用以使其具有动画效果。

为了检测何时UserInterfaceStyle发生变化(并相应地更新状态栏颜色),所有视图和视图控制器都有委托功能。所以知道:

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. 因此,如果您使用的是 generalnavigationControllertabBarController,带有这些代码的自定义类就足够了。

于 2019-10-28T10:57:56.477 回答