How to add inner shadow to UIView with rounded corners

Viewed 1334

I have to add an inner shadow to a UIView that has rounded corners.

I saw several answers on SO that add inner shadows to UIViews but they don't work as I want to, because they add the shadow to the whole rectangle, not accounting for the rounded corners.

See this image as an example of what I would like to achieve:

enter image description here

1 Answers

It's a trick. You give shadow and border to same view, the shadow will fall inside the view. please make sure the background color of view is clear. use the below code for reference.

yourView.layer.shadowColor = UIColor.gray.cgColor
yourView.layer.shadowOpacity = 0.3
yourView.layer.shadowOffset = CGSize.zero
yourView.layer.shadowRadius = 6
yourView.layer.masksToBounds = true
yourView.layer.borderWidth = 1.5
yourView.layer.borderColor = UIColor.white.cgColor
yourView.layer.cornerRadius = imageView.bounds.width / 2
Related