All the solution are outdated.
After doing research for about 3 hours, Here is the best solution for all iOS versions in Swift 5.5
I am making an extension of UIViewController which will be easy to use on any viewController.
// MARK: Change status bar color
extension UIViewController {
public func setStatusBarBackgroundColor(_ color: UIColor) {
if #available(iOS 13.0, *) {
// get the window scene and status bar manager for iOS>13.0
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let statusBarManager = windowScene.statusBarManager
else {
return
}
// get the status bar height
let statusBarHeight: CGFloat = statusBarManager.statusBarFrame.size.height
let statusbarView = UIView()
// change your color
statusbarView.backgroundColor = color
view.addSubview(statusbarView)
statusbarView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
statusbarView.topAnchor.constraint(equalTo: view.topAnchor),
statusbarView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
statusbarView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
statusbarView.heightAnchor.constraint(equalToConstant: statusBarHeight)
])
} else {
let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
statusBar?.backgroundColor = color
}
}
}
If you have any confusion please let me know.
Also if you want to change status bar color according to view controller then follow this step
first changethe "View controller-based status bar appearance" key in the Info.plist, make sure it is set to "YES" like below picture
and add this code.
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
Note
The preferredStatusBarStyle property won't get called if the view controller is embedded in another container view controller, e.g., UINavigationController.
so, you have to assign like this
class YourNavigationController: UINavigationController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
And If you want a navigation controller to give control of the status bar style to its children, override the childForStatusBarStyle property and return any child view controllers that you want to determine the status bar style.
override var childForStatusBarStyle: UIViewController? {
return visibleViewController
}
Chuck this code in your YourNavigationController class.
Best up luck!!!
UIView
is private. I am curious to see if your app gets approved using this. – Georgiegeorgina