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

Change the background color StatusBar based on the current ViewController?

我希望能够更改我的应用程序的状态栏背景颜色,在 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
    }

试试下面的代码,可能适合你。

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

如果我没理解错的话,你需要找到当前显示的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
        }
    }