我的应用程序有 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/