Papi
Papi

Reputation: 345

Top most element on ZStack is wider than screen

I have this ZStack with a background which is wider than the device width, but I would like to put a VStack on top of that which stays within the bounds of the screen. The problem with this code is that the VStack is just as wide as the other elements in the ZStack.

Any idea on how to fix this?

ZStack {
    Group {
        VStack {
            Image("EmptyPhoto")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .edgesIgnoringSafeArea(.vertical)
                .frame(height: 600)
            Spacer()
        }
        
        Color.black.opacity(0.5)
            .edgesIgnoringSafeArea(.vertical)
        
        VStack {
            Color.black.opacity(0.0)
            
            Spacer()
                .frame(height: 0)
            
            LinearGradient(gradient: Gradient(colors: [Color.black.opacity(0.0), Color.black, Color.black]), startPoint: .top, endPoint: .bottom)
        }
        .edgesIgnoringSafeArea(.vertical)
    } // Background
    
    VStack {
        Picker(selection: $filterPicker, label: EmptyView()) {
            Text("Friends").tag(1)
            Text("World").tag(2)
        }
        .pickerStyle(.segmented)
        
        HStack {
            Text("@gallapagos")
                .foregroundColor(Color.white)
            Spacer()
            
        }
        Spacer()
    }
    .padding()
}

Upvotes: 1

Views: 739

Answers (2)

Vu Anh Le Ha
Vu Anh Le Ha

Reputation: 1

I would just do:

.frame(maxWidth: UIScreen.main.bounds.size.width)

Upvotes: 0

Papi
Papi

Reputation: 345

Fixed by using the following:

extension UIScreen{
   static let screenWidth = UIScreen.main.bounds.size.width
}

Placed this below // Background

.frame(maxWidth: UIScreen.screenWidth)

Upvotes: 2

Related Questions