0

I was changing the background color of the status bar.

I tried to use the following code but I get warnings in Xcode 14 as my app support iOS 15 and above.

func setupStatusBar() {
    if let statusBarFrame = UIApplication.shared.windows.first?.windowScene?.statusBarManager?.statusBarFrame {
        let statusBarView = UIView(frame: statusBarFrame)
        statusBarView.backgroundColor = UIColor.yellow
        UIApplication.shared.windows.first?.addSubview(statusBarView)
    }
}
RTXGamer
  • 3,215
  • 6
  • 20
  • 29
  • oh @HangarRash sorry for that comment, please check this answer https://stackoverflow.com/questions/39802420/change-status-bar-background-color-in-swift-3 – Chandaboy Aug 01 '23 at 06:37
  • Does this answer your question? [Change status bar background color in iOS13](https://stackoverflow.com/questions/57726365/change-status-bar-background-color-in-ios13) – HangarRash Aug 01 '23 at 06:42
  • Thank you for your response. I am looking for an approach that does not use keywindow as that is depreciated in iOS 15. – ashima passi Aug 01 '23 at 08:36
  • @ashimapassi Did you look through all of the answers in the linked question? Not all make use of the deprecated `keyWindow`. – HangarRash Aug 01 '23 at 17:49

1 Answers1

0

App-level

You can change the status bar background color for all view controllers in your app by setting the UIStatusBarStyle property in the AppDelegate.swift file. The following code shows how to do this:

   func application(_ application: UIApplication,
               didFinishLaunchingWithOptions launchOptions:
               [UIApplication.LaunchOptionsKey: Any]?) -> Bool { 
    // Set the status bar background color to yellow. 
UIApplication.shared.statusBarStyle = .lightContent return true 
}

View controller-level

You can also change the status bar background color for a specific view controller by overriding the preferredStatusBarStyle property. The following code shows how to do this:

class MyViewController: UIViewController {
  override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
  }
}

Note that the preferredStatusBarStyle property is deprecated in iOS 15. However, it is still supported for backward compatibility.

Here is an example of how to change the background color of the status bar in a SwiftUI view:

struct MyView: View {
  @State private var statusBarColor = UIColor.yellow

  var body: some View {
    ZStack {
      // Your view content here...
      Color(statusBarColor)
        .statusBarBackground()
    }
  }
}

The statusBarBackground() modifier is a SwiftUI modifier that applies the background color of the view to the status bar.