Search code examples
swiftswiftuishadow

SwiftUI: Shadow on view in VStack?


I have the following code:

struct ViewA: View {
        
    var body: some View {
        Rectangle()
            .fill(Color(.yellow))
    }
}
    
struct ViewB: View {
        
    var body: some View {
        Rectangle()
            .fill(Color(.white))
    }
}
    
struct ViewC: View {
        
    var body: some View {
        Rectangle()
            .fill(Color(.blue))
    }
}


struct TestView: View {


    var body: some View {
        
        GeometryReader { geo in
            
            
            VStack(spacing: 0) {
                
                ViewA()
                    .frame(width: geo.size.width, height: geo.size.width/4, alignment: .center)
                    .shadow(color: .black, radius: 10, x: 0, y: 10)
                
                ViewB()
                
                ViewC()
                    .frame(width: geo.size.width, height: 100, alignment: .center)
                    .shadow(color: .black, radius: 10, x: 0, y: 0)
                    .opacity(0.8)
                
            }
            
        }
    }
}

It draws:

enter image description here

The shadow at the bottom Blue over White view (ViewC over ViewB) shows up. I want the yellow view (ViewA) to drop a shadow on top of the white view.

I want the white view to appear as if it were under both the top view (yellow) and the bottom view (blue).

I am not sure how to organize the views so that the top view also drops shadow on the middle view.

How would I accomplish this?


Solution

  • You could apply zindex modifier to ViewA. For example .zIndex(.infinity). It will put ViewA on top of everything. https://developer.apple.com/documentation/swiftui/view/zindex(_:)