Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - How do I change the background color of a View?

People also ask

How do I change the background in SwiftUI?

SwiftUI doesn't have a dedicated modifier for displaying background colors or images, but instead lets us specify any kind of background view using its background() modifier. To be clear, you can use any view as your background – another text view if you wanted, for example.

How do you give the background a color in Swift?

Find the view or view controller you want to change the background color of. Open it up in the interface builder and open the Attributes Inspector. Find the background color field and set it to the color you want.


Screen's Background Color

(As of Xcode Version 13)

I'm not sure if the original poster meant the background color of the entire screen or of individual views. So I'll just add this answer which is to set the entire screen's background color.

Using ZStack

var body: some View {
    ZStack {
            Color.purple
                .ignoresSafeArea()
            
            // Your other content here
            // Other layers will respect the safe area edges
    }
}

I added .ignoresSafeArea() otherwise, it will stop at safe area margins.

Using Overlay Modifier

var body: some View {
    Color.purple
        .ignoresSafeArea(.vertical) // Ignore just for the color
        .overlay(
            VStack(spacing: 20) {
                Text("Overlay").font(.largeTitle)
                Text("Example").font(.title).foregroundColor(.white)
        })
}

Note: It's important to keep the .ignoresSafeArea on just the color so your main content isn't ignoring the safe area edges too.

iOS 15

iOS 15/Xcode 13 has introduced some changes to the way Styles work with the edges of safe areas.

From my observation, the rule is: If the style touches the safe area edge, it will bleed into the safe area.

This gives you more options for setting a background color/style.

What is a Style?

A Style can be:

  • Colors
  • Materials (blur effects)
  • Hierarchical views (.secondary, .tertiary, .quaternary)
  • Gradients

Using Background

Because the background of the VStack touches the edge of the safe area, the purple color will bleed into the safe area.

var body: some View {
    VStack {
        Text("Hello, World!")
        Divider()
        Spacer()
    }
    .background(Color.purple)
}

TabView

In iOS 15 the TabView is no longer translucent. Meaning the background color will bleed right into it.

Background color in TabView

If you want to provide a custom style for your TabView, you can add another Style that touches the bottom safe area edge so that bleeds into your TabView. For example:

var body: some View {
    TabView {
        VStack {
            Text("Hello, World!")
            Divider()
            Spacer()
            // Bleeds into TabView
            Rectangle()
                .frame(height: 0)
                .background(.thinMaterial)
        }
        .background(Color.purple)
        .tabItem {
            Text("Tab 1")
            Image(systemName: "wifi")
        }
    }
}

TabView with Style

NavigationView

The same thing that happens to TabView will also happen with NavigationView.

To customize the NavigationView style, add a style that will touch the top safe area edge and it will bleed into the NavigationView:

var body: some View {
    NavigationView {
        VStack {
            // Bleeds into NavigationView
            Rectangle()
                .frame(height: 0)
                .background(.ultraThinMaterial)
            Text("Hello, World!")
            Divider()
            Spacer()
        }
        .background(Color.purple)
        .navigationTitle(Text("Style"))
    }
}

NavigationView with Style

I'm totally open to other ways of accomplishing this. Leave a comment or edit this answer if you know of other ways.


You can do something like:

.background(Color.black)

around your view.

eg. from the default template (I am encompassing it around a Group):

    var body: some View {
        VStack {
          Text("Hello SwiftUI!")
        }
       .background(Color.black)
    }

To add some opacity to it, you can add the .opacity method as well:

.background(Color.black.opacity(0.5))

You can also make use of the inspect element of the view by CMD + click on the View and clicking Show SwiftUI Inspector > Background > Your Color

Inspect View

Inspect Detail View


Fill the entire screen:

var body: some View {
    Color.green.edgesIgnoringSafeArea(.all)
}
Code Result
Image of code Screen is completely green, even area around notch

like this

struct ContentView : View {
    @State var fullName: String = "yushuyi"
    var body: some View {        
        VStack
            {
                TextField($fullName).background(SwiftUI.Color.red)
                Spacer()
        }.background(SwiftUI.Color.yellow.edgesIgnoringSafeArea(.all))
    }
}

For List:

All SwiftUI's Lists are backed by a UITableViewin iOS. so you need to change the background color of the tableView. But since Color and UIColor values are slightly different, you can get rid of the UIColor.

struct ContentView : View {
    init(){
        UITableView.appearance().backgroundColor = .clear
    }
    
    var body: some View {
        List {
            Section(header: Text("First Section")) {
                Text("First Cell")
            }
            Section(header: Text("Second Section")) {
                Text("First Cell")
            }
        }
        .background(Color.yellow)
    }
}

Now you can use Any background (including all Colors) you want


Also 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 very common issue is we can not remove the background color of SwiftUI's HostingViewController (yet), so we can't see some of the views like navigationView through the views hierarchy. You should wait for the API or try to fake those views (not recommended).