UIKit-ShadowDrawing Bug

bug I meeted: use self.addShadow(.black, sRadius: 2, sOpacity: 0.2, offset: (-1, -1)) not works, addShadow is below

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(rect: rect.offsetBy(dx: offset.0, dy: offset.1))
self.layer.shadowPath = path.cgPath

however, I added it after snp constrains wrote, but when I break at this line, I found that it's frame is equal to .zero. After about a hr struggling with articles, I knowed that it's frame changes after layoutSubviews is called

so I wrote like this

override func layoutSubviews() {
self.addShadow(.black, sRadius: 2, sOpacity: 0.2, offset: (-1, -1))

which works perfectly.

文章作者: X Mεl0n
文章链接: http://www.zrzz.site/posts/a306ac29/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 X Mεl0n | 随手记