Reputation: 3637
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.
I'm not sure how to check which view controller is the current view controller. It should be an if/else statement. I have this in my 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
}
Upvotes: 0
Views: 694
Reputation: 3009
If I understand you correctly, you need to find currently displayed 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:
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
}
}
Upvotes: 1
Reputation: 47049
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.
}
Upvotes: 0