SwiftUI, shadow only for container
Asked Answered
K

3

33

For example, I have this view:

import SwiftUI

struct TarifsScreen: View {  
    var body: some View {        
        GeometryReader { geometry in            
            VStack {                
                VStack {
                    Spacer()
                    Text("Text1")
                    Spacer()
                    Text("Text2")
                    Spacer()
                    Text("Text3")
                    Spacer()                    
                }
            }
            .frame(width: geometry.size.width, height: geometry.size.height)
            .shadow(color: Color.white, radius: 10, x: 0, y: 0)
        }
    }
}

How can I apply shadow only for VStack, not for all elements inside VStack? May be I can do it with ZStack and two containers?

Krusche answered 18/3, 2020 at 12:54 Comment(0)
T
65

Add background and apply shadow to it, like in below example

demo

  VStack {
    ...
  }
  .background(Color.white // any non-transparent background
    .shadow(color: Color.red, radius: 10, x: 0, y: 0)
  )
  .frame(width: geometry.size.width, height: geometry.size.height)
Thaxton answered 18/3, 2020 at 13:16 Comment(0)
S
9

Also for a specific view:

var body: some View {
    Text("SwiftUI is Awesome").padding().background(
        Rectangle()
            .fill(Color.white)
            .cornerRadius(12)
            .shadow(
                color: Color.gray.opacity(0.7),
                radius: 8,
                x: 0,
                y: 0
            )
    )
}

Reference from here.

Result:

enter image description here

Standby answered 4/11, 2022 at 1:12 Comment(0)
L
2

If you don't want to add fills or backgrounds, you can better override the .shadow modifier on the child views with a .clear color, to "stop" the shadow modifier from propagating down the hierarchy.

VStack { 
  // View with shadow
  ...
  VStack {
    // View without shadow
    ...
  }
  .shadow(color: .clear, radius: 0) // Override shadow
}
.shadow(color: .black.opacity(0.3), radius: 10)

For example if you are using a png image, the other answers would render the alpha channel with a solid color, which is not ideal.

Liggins answered 29/1, 2023 at 17:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.