ios - 如何使 preferredStatusBarStyle 成为一个函数

标签 ios swift xcode

我的应用程序有 12 个 ViewController,我希望从设置页面更改每个 View Controller 的状态栏。 现在,我使用一个函数来完成它,该函数已放入“CommonFuncs”类中,然后我从每个 ViewController 调用该函数:

CommonFuncs.setStatusBarColor()

它使用这个已弃用的调用:

UIApplication.shared.statusBarStyle = .lightContent

这让我可以使用一次调用从“设置”页面为应用程序中的所有 View 设置状态栏。

现在我需要更新并删除已弃用的函数,但似乎替换需要每个 ViewController 的代码:

override var preferredStatusBarStyle: UIStatusBarStyle {
    if activeForeColorName == "white"{
        return .lightContent
    }else if activeForeColorName == "black"{
        return .default
    }else{
        return .lightContent
    }
}

加上我在 viewWillAppear 中使用的刷新:

override func viewWillAppear(_ animated: Bool) {
    setNeedsStatusBarAppearanceUpdate()
}

这真的很痛苦,因为需要将相同的代码放入 12 个单独的 ViewController。

有没有办法将这段代码移动到一个函数中,或者使用另一个适用于整个应用的状态栏调用?

最佳答案

您可以在 UIViewController 扩展中移动它,例如

extension UIViewController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        if Configs.statusBarColor == "black"{
            return .default
        } else {
            return .lightContent
        }
    }

    //swizzle viewWillAppear and viewWillDisappear methods and observe for statusBar color change notifications 

    //...
    //swizzling code here...
    //...       

    func swizzledViewWillAppear(_animated: Bool) {
        self.swizzledViewDidLoad(animated)

        NotificationCenter.default.addObserver(self, selector: #selector(updateStatusBarAppearance), name: NSNotification.Name("updateStatusBarColorNotification"), object: nil)
    }

    func swizzledViewWillDisappear(_animated: Bool) {
        swizzledViewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }

    @objc func updateStatusBarAppearance() {
        setNeedsStatusBarAppearanceUpdate()
    }    
}

然后,每当您更改 Configs.statusBarColor(或者在您的情况下为 activeForeColorName)时,只需发布​​名称为 updateStatusBarColorNotification 的通知

关于ios - 如何使 preferredStatusBarStyle 成为一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53355554/

相关文章:

ios - 如何使用面向协议(protocol)的编程来改进我的 Swift 代码?

ios - 什么时候必须将框架和库链接到 XCode 项目?

swift - 在 SwiftUI 中用波浪动画填充圆圈

ios - 将自动完成添加到现有 TableViewController Swift 中的 TextField

ios - C 如何打印 CFNumberRef

ios - 如何从十六进制字符串获取 NSData?

ios - popToRootViewController 之后选项卡栏不显示

javascript - iOS uiwebview 在加载整个 html 文件之前触发 finishLoad 事件

ios - 触摸屏幕时以 NSException 类型的未捕获异常终止

View 出现后应用 iOS 8/XCode 6 自动布局约束