如果直接在collectionView cellForItemAt上配置单元格属性,Mike Sabatini的答案就可以很好地工作,但是如果尝试在自定义UICollectionViewCell子类的awakeFromNib()中设置它们,则会在设置了该属性的设备上以错误的bezierPath结尾与先前在情节提要(IB)中设置的宽度和高度不匹配。
对我来说,解决方案是在UICollectionViewCell的子类中创建一个func,然后从cellForItemAt调用它,如下所示:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) as? CustomCollectionViewCell{
cell.configure())
return cell
}
else {
return UICollectionViewCell()
}
}
在CustomCollectionViewCell.swift上:
class CustomCollectionViewCell: UICollectionViewCell{
func configure() {
contentView.layer.cornerRadius = 20
contentView.layer.borderWidth = 1.0
contentView.layer.borderColor = UIColor.clear.cgColor
contentView.layer.masksToBounds = true
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 2.0)
layer.shadowRadius = 2.0
layer.shadowOpacity = 0.5
layer.masksToBounds = false
layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: contentView.layer.cornerRadius).cgPath}
}