How to change status bar text color immediately in Swift in iOS 13

后端 未结 1 1196
我寻月下人不归
我寻月下人不归 2021-01-14 14:06

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

相关标签:
1条回答
  • 2021-01-14 15:01

    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 }
    

    these two variables help you to change the status bar. Note that you can call setNeedsStatusBarAppearanceUpdate inside an animation block to make it animatable.

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

    And this is the function:

    func updateStatusBarColor() {
        switch traitCollection.userInterfaceStyle {
        case .unspecified: statusBarStyle = .default
        case .light: statusBarStyle = .darkContent
        case .dark: statusBarStyle = .lightContent
        }
    }
    

    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.

    0 讨论(0)
提交回复
热议问题