UICollectionViewDelegateFlowLayout 没有改变单元格边界
UICollectionViewDelegateFlowLayout is not changing cell bounds
我在为 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)
有什么问题?
问题是如果您的单元格已布局,bounds/frame 会发生变化。
将此添加到您的 collectionViewCell - 子类:
override func layoutSubviews() {
super.layoutSubviews()
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.contentView.layer.cornerRadius).cgPath
}
我在为 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)
有什么问题?
问题是如果您的单元格已布局,bounds/frame 会发生变化。
将此添加到您的 collectionViewCell - 子类:
override func layoutSubviews() {
super.layoutSubviews()
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.contentView.layer.cornerRadius).cgPath
}