根据当前的ViewController更改背景颜色StatusBar?

时间:2017-11-28 10:31:59

标签: ios swift uistatusbar

我希望能够将我的应用的状态栏背景颜色更改为3个特定UIViewControllers上的透明,并将其余部分设置为其他内容。

我不确定如何检查哪个视图控制器是当前视图控制器。它应该是if / else语句。我在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
    }

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要找到当前显示的viewController。这个扩展应该做一个技巧:

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

然后,在需要查找当前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
        }
    }

答案 1 :(得分:0)

尝试使用以下代码,可能适合您。

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.
}