mdcq
mdcq

Reputation: 2026

SwiftUI large Image in ZStack breaks alignment of other layers

I have a simple ContentView consisting of a VStack with some text and a spacer.

VStack {

    Text("Hello")

    Spacer()

    Text("World")
}

I want to put a background image behind it. I tried using ZStack.

ZStack {

    Image("background")

    VStack {

        Text("Hello")

        Spacer()

        Text("World")
    }

But now the VStack doesn't respect the safe area anymore.

Also in landscape mode the VStack doesn't rescale at all, effectively moving its contents out of view.

Why does the Image affect the VStack? I thought the ZStack keeps layers "independent"?

Upvotes: 6

Views: 2020

Answers (2)

Sheetal Shinde
Sheetal Shinde

Reputation: 529

struct AlphabetView: View {
        var body: some View {
            VStack {
                Text("Home Screen")
                List(0..<17) { item in
                    AlphabetCell(cellCount:item)
                        .listRowSeparator(.hidden)
                }.scrollContentBackground(.hidden)
            }.background(
                Image("wallpaper1")
                    .resizable()
                    .scaledToFill()
            )
            
        }
    }

Upvotes: 0

Cenk Bilgen
Cenk Bilgen

Reputation: 1435

What's happening here is correct, if the size of the "background" image is large and roughly the size of the screen.

The size of the ZStack view is determined by the size of its layers. It's made big enough to just encapsulate them. Here it looks like the overall size is determined by the "background" image size. That in turn effects the size of the VStack layer because its Spacer will expand to fill to that size.

Resize your Image to what you want. Also look at using the background() modifier on the VStack instead of a ZStack.

How you want the Image to look in landscape mode is up to you, but it won't resize or flip by itself.

Upvotes: 7

Related Questions