By default the status bar is present, but in landscape orientation on an iPhone it is absent. The ViewController can control the behavior and look of status bar.
We can control the status bar style by overriding
override var preferredStatusBarStyle: UIStatusBarStyle { //return .lightContent return .default}
We have two options. First one is .default for dark text and the second one is .lightContent for light text.
We can control the status bar visibility by overriding
override var prefersStatusBarHidden: Bool { return false // true}
But if we want to update the status bar in any situation then we can call the setNeedsStatusBarApperanceUpdate() on our ViewController. If we want to perform animation while updating the appearance of the status bar we should override
override var preferredStatusBarUpdateAnimation:
UIStatusBarAnimation { return .slide // .fade, .none}
The default animation is .fade.
Now we are going to apply everything in a demo project where there will be a button and on clicking the button we will show & hide the status bar with animation. Create a new project in Xcode and create a new ViewController named RootViewController by subclassing UIViewController.
Modify the following function of your AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow() window?.rootViewController = RootViewController() window?.makeKeyAndVisible() return true}
Now your RootViewController should look like this.
import UIKitclass RootViewController: UIViewController { var isHidden = false let button: UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("Click Me", for: .normal) button.setTitleColor(.black, for: .normal) button.backgroundColor = .white return button }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .gray self.view.addSubview(button) NSLayoutConstraint.activate([ button.widthAnchor.constraint(equalToConstant: 200), button.heightAnchor.constraint(equalToConstant: 50), button.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), button.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor)]) button.addTarget(self, action: #selector(handleClick), for: .touchUpInside) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override var prefersStatusBarHidden: Bool { return isHidden } override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .slide } @objc func handleClick() { self.isHidden.toggle() UIView.animate(withDuration: 0.4){ self.setNeedsStatusBarAppearanceUpdate() self.view.layoutIfNeeded() } }}
Run the project, if everything goes well then you will see a button with text Click Me appears right in the middle of your simulator. Click the button to see the status bar showing/hiding with slide animation.