KelvinJin / AnimatedCollectionViewLayout

A UICollectionViewLayout subclass that adds custom transitions/animations to the UICollectionView without effecting your existing code.
MIT License
4.7k stars 347 forks source link

How do we add spacing between cells for parallax effect? #47

Closed JayceBryce closed 5 years ago

JayceBryce commented 5 years ago

I'm currently trying to set spacing between my collection view cells. The issue is every time I scroll horizontally the cell does not reset back to where is should be.

Please Look at image bellow!

Here is my code:

extension ImageCollectionViewController: UICollectionViewDelegateFlowLayout {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return Int(Int16.max)
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let c = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath)

    if let cell = c as? SimpleCollectionViewCell {
        let i = indexPath.row % vcs.count
        let v = vcs[i]
        cell.bind(color: v.0, imageName: v.1)
        cell.clipsToBounds = animator?.1 ?? true
    }

    return c
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    guard let animator = animator else { return view.bounds.size }
    return CGSize(width: view.bounds.width / CGFloat(animator.2), height: view.bounds.height / CGFloat(animator.3))
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return .zero
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 10
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}
}

Also here are images showing what happens:

CollectionView

KelvinJin commented 5 years ago

Hey JayceBryce. I think the issue here is related to this stackoverflow question https://stackoverflow.com/questions/29658328/uicollectionview-horizontal-paging-not-centered.

You can potentially also override the targetContentOffset method of AnimatedCollectionViewLayout to make sure when the user stops scrolling, the cell will snap to the right offset. Regardless, I don't think the animator itself needs to be changed.

JayceBryce commented 5 years ago

Ok thanks!

KelvinJin commented 5 years ago

I'll close this issue for now. If you have further questions, feel free to reopen it.