Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change background color of the NavigationView in SwiftUI?

Tags:

ios

swift

swiftui

I'm trying to change background color of the NavigationView (not navigation bar) using this code:

NavigationView {
    Text("Text")
}
.background(Color.clear)

But it doesn't work. Also, I tried to change UIView appearance:

UIView.appearance().backgroundColor = UIColor.black

But it doesn't work too.

The actual result is presented below:

enter image description here

The desired result is:

enter image description here

Does anyone know how to do this?

like image 778
Ilya Kharabet Avatar asked Aug 28 '19 05:08

Ilya Kharabet


People also ask

How do I change the background color in SwiftUI?

The first way would be to use the . background modifier and pass Color which is a view in SwiftUI. The second approach would be using ZStack and add one color or multiple colors wrapped in VStack for vertical and HStack for horizontal layout.

How do I change the background color in SwiftUI status bar?

Go to your main view or any view that you want to modify and try it out. Created a property called statusBarModifier and assigned the background color and text color. Then I wrapped a VStack within the body of my view and assigned a . modifier where I passed in the statusBarModifier we created.

How do I change the color of my UINavigationBar?

Open the project's storyboard file. Select the UINavigationBar from your UINavigationController scene. In the Attributes Inspector pane turn on these Appearances: “Standard”, “Compact”, “Scroll Edge”, and “Compact Scroll Edge”. For all four appearances, set the “Background” to “System Red Color”, for example.

How do I change the color of a list in SwiftUI?

We can change the background color of a list row in SwiftUI with listRowBackground(_:) modifier. To set a list row background color, add listRowBackground(_:) modifier to the list row item.


1 Answers

First look at this result:

View hierarchy

As you can see, you can set the color of each element in the View hierarchy like this:

struct ContentView: View {

    init(){
        UINavigationBar.appearance().backgroundColor = .green 
        //For other NavigationBar changes, look here:(https://stackoverflow.com/a/57509555/5623035)
    }

    var body: some View {
        ZStack {
            Color.yellow
            NavigationView {
                ZStack {
                    Color.blue
                    Text("Some text")
                }
            }.background(Color.red)
        }
    }
}

And the first one is window:

window.backgroundColor = .magenta

The issue you faced is we can not remove the background color of SwiftUI's HostingViewController (yet), so you can't see the navigationView (What you called) through the views hierarchy. You should wait for the API or try to fake the navigation view (not recommended).

like image 109
Mojtaba Hosseini Avatar answered Sep 21 '22 00:09

Mojtaba Hosseini