How to apply shadow to interior views in SwiftUI?
You can use clipped()
here to fix this
VStack() {
Text("Text")
.background(Color.red)
.padding()
.padding()
Text("Text")
.background(Color.purple)
.padding()
}
.padding()
.background(Color.white)
.clipped()
.shadow(color: Color.red, radius: 10, x: 0, y: 0)
Output:
Hope it is helpful :)
For me it also worked to apply the shadow to the background instead of the Stack, e.g:
VStack {
// ...
}.background(Rectangle().fill(Color.white).shadow(radius: 8))
There is a dedicated modifier for this - compositingGroup
.
From documentation:
/// Wraps this view in a compositing group.
///
/// A compositing group makes compositing effects in this view's ancestor
/// views, such as opacity and the blend mode, take effect before this view
/// is rendered.
/// [...]
/// This limits the scope of [...] change to the outermost view.
VStack {
Text("Text")
.background(Color.red)
.padding()
.padding()
Text("Text")
.background(Color.purple)
.padding()
}
.padding()
.background(Color.white)
.compositingGroup()
.shadow(color: Color.red, radius: 10, x: 0, y: 0)