0

我在设置UICollectionViewCell具有相对collectionView边界宽度的阴影路径时遇到问题。

我使用情节提要约束,在方法中设置阴影并使用方法AwakeFromNib调整单元格大小sizeForItemAt

 //cell awakeFromNib    
    override func awakeFromNib() {

    self.backgroundColor = UIColor.white

    self.contentView.layer.cornerRadius = 2.0
    self.contentView.layer.borderWidth = 1.0
    self.contentView.layer.borderColor = UIColor.clear.cgColor
    self.contentView.layer.masksToBounds = true

    self.layer.shadowColor = UIColor.black.cgColor
    self.layer.shadowOffset = CGSize(width: 0, height: 2.0)
    self.layer.shadowRadius = 2.0
    self.layer.shadowOpacity = 0.5
    self.layer.masksToBounds = false
    self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.contentView.layer.cornerRadius).cgPath
}



// collection view method
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let height: CGFloat = 288

    return CGSize(width: collectionView.bounds.size.width-20, height: height)
}

单元格边界:

AwakeFromNib方法 - (307.0, 288.0)

预期 - (300.0, 288.0)

问题是什么?

4

1 回答 1

0

问题是如果你的单元格被布局,边界/框架正在改变。

将此添加到您的 collectionViewCell - 子类:

    override func layoutSubviews() {
    super.layoutSubviews()
        self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds,  cornerRadius: self.contentView.layer.cornerRadius).cgPath
    }
于 2019-02-07T15:29:10.947 回答