0

Multiple placed in my app, I have views with both shadows and corner radii. I tried adding a new view, and suddenly the code I was reusing doesn't work anymore. I can only set a corner radius or a shadow, depending on what I put for masksToBounds. Here's the code I use for both the faulty view and my other views:

        itemCountLabel.layer.masksToBounds = false
        itemCountLabel.layer.cornerRadius = itemCountLabelSize / 2.0
        itemCountLabel.layer.shadowColor = UIColor.black.cgColor
        itemCountLabel.layer.shadowOpacity = 0.25
        itemCountLabel.layer.shadowRadius = 5
        itemCountLabel.layer.shadowOffset = CGSize(width: 4, height: 4)
        contentView.addSubview(itemCountLabel)
Kevin2566
  • 425
  • 8
  • 20

2 Answers2

0

It's not possible to implement as you've tried. Shadow is always applied outside the bounds of the UIView and the cornerRadius will not be visible without masking the bounds of UIView. So, better add a UIView behind the UILabel and to reuse the function write an extension of UIView that returns a UIView contains the view you want to apply the shadow.

Catherine
  • 199
  • 6
  • It is possible, as I state in my question I have done this multiple times throughout my app with the exact same code and without adding an extra `UIView`. – Kevin2566 Mar 31 '20 at 05:58
  • @Kevin2566 - While Catherine might not have been correct that this problem manifests itself for all `UIView`, her prescription seems reasonable for the `UILabel` scenario. – Rob Mar 31 '20 at 06:06
0

Here you need to use two different views one to round the corners and the other behind it to show the shadow, As both these properties don’t work together because of the Mask To Bounds and Clip To Bounds features. As corner radius needs to clip the edges which might can contain the shadow.

So to have both of the things use a shadow view behind the view which you want to have rounded corners.

Apps Maven
  • 1,314
  • 1
  • 4
  • 17