I have a horizontal UICollectionView. I want to make the cells overlap each other by a certain amount of 60 pixels so that the second cells overlaps the first by 60 pixels a
This doesn't blow up using UICollectionViewDiffableDataSource when calling numberOfItemsInSection)
(N.B. the other solutions fix the collectionViewContentSize / I welcome an edit to fix this without calling numberOfItemsInSection.
var cellLayout = OverlapLayout()
cellLayout.scrollDirection = .horizontal
cellLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
cellLayout.itemSize = CGSize(width: 44, height: 44)
class OverlapLayout: UICollectionViewFlowLayout {
var overlap: CGFloat = 20
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let arr = super.layoutAttributesForElements(in: rect)!
return arr.map { atts in
var atts = atts
if atts.representedElementCategory == .cell {
let ip = atts.indexPath
atts = self.layoutAttributesForItem(at: ip)!
}
return atts
}
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let atts = super.layoutAttributesForItem(at: indexPath)!
var xPosition = atts.center.x
if indexPath.item == 0 {
return atts
}else{
xPosition -= self.overlap * CGFloat(atts.indexPath.row)
atts.center = CGPoint(x: xPosition, y: atts.center.y)
return atts
}
}
}
// Requires Snapkit
class BubbleCell: UICollectionViewCell {
static let ID = "BubbleCell"
var magicCornerRadius = 22 // make this half the collectionview height
lazy var bubbleImageView: UIImageView = UIImageView(frame: .zero)
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupViews() {
self.backgroundColor = .clear
contentView.backgroundColor = .clear
// Hero Image
contentView.addSubview(bubbleImageView)
bubbleImageView.snp.remakeConstraints { (make) in
make.edges.equalToSuperview()
}
bubbleImageView.layer.cornerRadius = magicCornerRadius
bubbleImageView.layer.borderColor = UIColor.white.cgColor
bubbleImageView.layer.borderWidth = 2
bubbleImageView.clipsToBounds = true
bubbleImageView.image = kPlaceholderImage
bubbleImageView.contentMode = .scaleAspectFill
}
func configureCell(imageURL: URL) {
// use third party library to fetch image here / that caches eg. SDWebImage
}
}