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.