需求:cell中有一个卡片子控件,需要设置shadowPath属性来实现四周阴影效果。动态获取子控件的大小,来确定path
问题:采取自动布局,cell自动设置行高。layoutSubViews方法中打印子控件frame值,为zero
解决办法:调用setNeedsLayout,layoutIfNeeded及时更新布局
代码:
override func layoutSubviews() {
super.layoutSubviews()
contentView.setNeedsLayout()
contentView.layoutIfNeeded()
containerView.layer.shadowColor = UIColor.black.cgColor
containerView.layer.shadowOpacity = 0.2
containerView.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
let path = UIBezierPath(roundedRect: CGRect(x: -2, y: -2, width: containerView.width+4, height: containerView.height+4), cornerRadius: 1.0)
containerView.layer.shadowPath = path.cgPath
}
网友评论