如何给带圆角的 UIView 添加内阴影

How to add inner shadow to UIView with rounded corners

我必须向圆角的 UIView 添加内阴影。

我在 SO 上看到了几个向 UIView 添加内部阴影的答案,但它们并没有像我想要的那样工作,因为它们将阴影添加到整个矩形,而不是圆角。

将此图片作为我想要实现的示例:

这是一个技巧。您为同一视图提供阴影和边框,阴影将落在视图内。请确保视图的背景颜色清晰。使用以下代码作为参考。

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