Search code examples
iosswiftuikit

Drop a shadow behind multiple UIViews


In this view

this

there are multiple subviews. Now I configured the views to drop a shadow as shown in the screenshot: The views are dropping the shadow also over the other views. Do you see a way to easily drop the shadow behind all views? So z-index of all the shadows < z-index of all the views.

I already tried to create an additional view for each box and placed all of this shadow views behind all boxes. This kind of works. But there is a lack when moving the boxes around using a PanGesture. Also this design looks a it messy. At the moment, it's a clear design to have one UIView for each box.


Solution

  • You're thinking about the solution wrong. However in your own words, 'behind all views' is the answer.

    As you noticed, applying a shadow to each view will have overlapping shadows due to each views z-index.

    You mentioned creating an additional view for each box which is close to another solution but not quite. You could create a single container view and place all of the boxes inside this one container view. Then apply your shadow to the container view. This will give you your result, but will have horrible performance! Every time layoutSubviews is called, such as when a views frame changes, the shadows are recalculated. As you mentioned, you're using a pan gesture, so moving a box slightly will layout the subviews a few dozen times.

    The solution you should go with is to create 2 container views which are sibling views. For every colored view you create, add it to the top container view and create another view which will be added to the bottom container view, lets call it the shadow container view. Use constraints on the views inside of the shadow container so their top, leading, bottom and trailing are equal to their equivalent view in the top container view. Next add a shadow to the views inside of the shadow container view and make sure to apply the layer.shadowPath! This shadow path is the key to prevent the shadow from being redrawn when you pan.

    If you don't understand and need an example let me know and I'll give you one.