Another Dude
Another Dude

Reputation: 1452

SwiftUI: background color for whole screen and not simple view?

I am trying to do something very simple, display a view with a background color, and in the center of this view, display a single label.

I tried this:

var body: some View {
    VStack {
        Text("Hello!")
    }
    .background(MyColors.blue)
    .ignoresSafeArea() 
}

Here is the given result:

enter image description here

What am I doing wrong?

Thank you for your help

Upvotes: 0

Views: 4436

Answers (2)

Another Dude
Another Dude

Reputation: 1452

I managed to get it working with this code:

var body: some View {
    ZStack {
        Style.Color.red
        VStack {
            Text("Hello!")
        }
    }
    .ignoresSafeArea()
}

I didn't understand first that background and rest of the view must be set on a different z-axis.

Upvotes: 3

the.blaggy
the.blaggy

Reputation: 885

You can do it like this:

Text("Hello!")
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .background(MyColors.blue)
    .ignoresSafeArea()

Source: https://www.hackingwithswift.com/articles/224/common-swiftui-mistakes-and-how-to-fix-them

Upvotes: 1

Related Questions