[英]Change the background color StatusBar based on the current ViewController?
I want to be able to change the status bar background color of my app, to transparent on 3 specific UIViewControllers
and set the rest to be something else. 我希望能够将我的应用程序的状态栏背景颜色更改为在3个特定的
UIViewControllers
上透明,并将其余设置为其他。
I'm not sure how to check which view controller is the current view controller. 我不确定如何检查哪个视图控制器是当前视图控制器。 It should be an if/else statement.
它应该是一个if / else语句。 I have this in my
AppDelegate
: 我的
AppDelegate
有这个:
extension UIApplication {
var statusBarView: UIView? {
return value(forKey: "statusBar") as? UIView
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
let appDelegate = UIApplication.shared.delegate as? AppDelegate
if let currentVC = appDelegate?.window?.rootViewController?.getCurrentlyDisplayedVC()
{
if currentVC is LoginVC || currentVC is RegisterVC || currentVC is LostPasswordVC {
UIApplication.shared.statusBarView?.backgroundColor = .clear
} else {
UIApplication.shared.statusBarView?.backgroundColor = Color_Main_Blue
}
}
UIApplication.shared.statusBarStyle = .lightContent
return true
}
If I understand you correctly, you need to find currently displayed viewController. 如果我对您的理解正确,则需要找到当前显示的viewController。 This extension should do a trick:
这个扩展应该可以解决问题:
extension UIViewController {
func getCurrentlyDisplayedVC() -> UIViewController {
if let presentedVC = presentedViewController {
return presentedVC.getCurrentlyDisplayedVC()
} else if let split = self as? UISplitViewController, let last = split.viewControllers.last {
return last.getCurrentlyDisplayedVC()
}
else if let nav = self as? UINavigationController, let top = nav.topViewController {
return top.getCurrentlyDisplayedVC()
}
else if let tab = self as? UITabBarController {
if let selected = tab.selectedViewController {
return selected.getCurrentlyDisplayedVC()
}
}
return self
}
}
Then, where you need to find current viewController, you call: 然后,在需要找到当前viewController的地方,调用:
let appDelegate = UIApplication.shared.delegate as? AppDelegate
if let currentVC = appDelegate?.window?.rootViewController?.getCurrentlyDisplayedVC() {
if currentVC is YourViewController {
//do what you need
(UIApplication.shared.value(forKey: "statusBar") as? UIView)?.backgroundColor = UIColor.white
} else {
//other checks
}
}
Try with below code, Might be work for you. 尝试以下代码,可能会为您工作。
override func viewWillAppear(animated: Bool) {
supper.viewWillAppear(animated)
UIApplication.shared.statusBarHidden = false
UIApplication.shared.statusBarStyle = .lightContent
let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
statusBar.backgroundColor = self.view.backgroundColor // or change as you want.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.