to use both effects

1
2
3
self.contentView.layer.cornerRadius = 5
self.contentView.layer.masksToBounds = true
self.contentView.addShadow(.black, sRadius: 1, sOpacity: 0.3, offset: (1, 1))

and addShadow in layoutSubviews function

1
2
3
4
5
6
7
8
9
10
11
func addShadow(_ sColor: UIColor, sRadius: CGFloat, sOpacity: Float, offset: (CGFloat, CGFloat), for changedRect: CGRect = .zero) {
let rect = changedRect == .zero ? self.bounds : changedRect
self.layer.shadowColor = sColor.cgColor
self.layer.shadowRadius = sRadius
self.layer.shadowOpacity = sOpacity
// 设置 shadowOffset 会产生离屏渲染
// self.layer.shadowOffset = CGSize(width: 5, height: 5)
let path = UIBezierPath(roundedRect: rect.offsetBy(dx: offset.0, dy: offset.1), cornerRadius: self.layer.cornerRadius)
self.layer.shadowPath = path.cgPath
self.layer.masksToBounds = false
}