iosiphoneswiftuiios13

Subview have parent's shadow, even with a background


So I just started developing with SwiftUI and I'm running in a small problem. Subviews are also displaying superview's shadow, even if the superview has a background. Does someone know how to fix this?

HStack {
    HStack {
        [...]
    }
    .padding(.leading, 12.0)
    .padding(.trailing, 4.0)
    .padding(.vertical, 16.0)
    .background(Color("lightGreen"))
    .cornerRadius(10)
}
.padding(8)
.background(Color.white)
.shadow(color: Color("tabShadow"), radius: 0.0, x: 0.0, y: -0.5)
.shadow(color: Color("tabShadow"), radius: 0.0, x: 0.0, y: 0.5)

As stated, the first HStack's shadow shouldn't be replicated into the child one, but it is. Only the first one though. Any hints?


Solution

  • Certain modifiers, when placed on a stack, are inherited by all their children. For instance, if you have a stack containing a bunch of Text views, you can place one .font() modifier on the stack and they will all be modified.

    It appears that .shadow() is one of those modifiers. As to why only one is inherited, I suspect that the designers of SwiftUI don't expect .shadow() to be called more than once on a particular view, and didn't test for that.

    If you are just trying to get a colored line across the top and bottom of the view, maybe try something like

    .background(Color.white)
    .background(Color("tabShadow").offset(x: 0, y: -0.5))
    .background(Color("tabShadow").offset(x: 0, y: 0.5))