Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Status bar color

Tags:

ios

swift

swiftui

Is there a way to change the status bar to white for a SwiftUI view?

I'm probably missing something simple, but I can't seem to find a way to change the status bar to white in SwiftUI. So far I just see .statusBar(hidden: Bool).

like image 755
keegan3d Avatar asked Jul 16 '19 18:07

keegan3d


People also ask

How do I change the color of my status bar in SwiftUI?

You can change the status bar's color and material by inserting a small view right behind it. Normally, all views are positioned below the status bar, but you can use edgesIgnoringSafeArea(. top) to push it past the safe area insets.

How do I hide status bar in SwiftUI?

Make sure your initial SwiftUI View is a Navigation view where you hide the status bar. Then if you navigate to a tab bar view or any subsequent views the status bar will be hidden.

How do I add a navigation bar in SwiftUI?

To show a Navigation Bar using SwiftUI, we should use the NavigationView component that is responsible for this purpose. It requires that we provide the Content that is a View type. The Content can be anything from a text field to scrollable content. In short, it can be any SwiftUI view.


2 Answers

The status bar text/tint/foreground color can be set to white by setting the View's .dark or .light mode color scheme using .preferredColorScheme(_ colorScheme: ColorScheme?).

The first view in your hierarchy that uses this method will take precedence.

For example:

var body: some View {   ZStack { ... }   .preferredColorScheme(.dark) // white tint on status bar } 
var body: some View {   ZStack { ... }   .preferredColorScheme(.light) // black tint on status bar } 
like image 140
Dan Sandland Avatar answered Oct 05 '22 17:10

Dan Sandland


As in the comments linked to I edited this question here

But to answer this question and help people find the answer directly:

Swift 5 and SwiftUI

For SwiftUI create a new swift file called HostingController.swift

import SwiftUI  class HostingController<ContentView>: UIHostingController<ContentView> where ContentView : View {     override var preferredStatusBarStyle: UIStatusBarStyle {         return .lightContent     } } 

Then change the following lines of code in the SceneDelegate.swift

window.rootViewController = UIHostingController(rootView: ContentView()) 

to

window.rootViewController = HostingController(rootView: ContentView()) 
like image 37
krjw Avatar answered Oct 05 '22 17:10

krjw