A simple way of implementing a parallax effect on a UICollectionView. With UICollectionViewParallaxCell, you will be able to easily implement a parallax effect on either a vertical or horizontal scroll.
Here is a video of a vertical scroll Demo
With the UICollectionViewParallaxCell, you have control over the following:
- Parallax effect:
- Vertical Scroll
- Horizontal Scroll
- Constraints
- Top Constraint
- Bottom Constraint
- Left Constraint
- Right Constraint
- ParallaxOffset speed
UICollectionViewParallaxCell is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'UICollectionViewParallaxCell'
*Note:This is assuming you have a UICollectionView currently created.
Once installed, go to your Custom UICollectionViewCell class and import UICollectionViewParallaxCell
import UICollectionViewParallaxCell
In your custom UICollectionViewCell class, inherit the UICollectionViewParallaxCell class.
class CustomParallaxCell: UICollectionViewParallaxCell {...}
Within that class declare a UIImage
class CustomParallaxCell: UICollectionViewParallaxCell {
var backgroundImage : UIImageView? {
didSet {
guard let imageView = backgroundImage else { return }
imageView.contentMode = .scaleAspectFill
setupbackgroundParallax(imageView: imageView, cornerRadius: 0, paddingOffset: paddingOffset, topConstraint: 0, bottomConstraint: 0, leadingConstraint: 0, trailingConstraint: 0)
}
}
}
}
*Note: paddingOffset is a variable declared within the UICollectionViewParallaxCell which by default is a CGFloat of 0. We will update the offset within the collectionView function, cellForItemAt.
In the class with your UICollectionView, go to your cellForItemAt function. Within in it declare the following:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CustomParallaxCell
cell.paddingOffset = 150 // declares the offset intensity of parallax
cell.backgroundImage = // pass through the UIImageView object to instantiate the setupbackgroundParallax function in the didSet
let bounds = collectionView.bounds // variable for the collectionView bounds
cell.parallaxOffset(collectionViewBounds: bounds, scrollDirecton: .vertical) // instantiate the inital bounds of the collectionview
return cell
}
Next call the scrollViewDidScroll function in the class with your UICollectionView. Declare the following:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let cells = collectionView.visibleCells as! [CustomParallaxCell]
let bounds = collectionView.bounds
for cell in cells {
cell.parallaxOffset(collectionViewBounds: bounds, scrollDirecton: .vertical)
}
}
Run project and enjoy.
Diego Bustamante, diegobust4545@icloud.com
UICollectionViewParallaxCell is available under the MIT license. See the LICENSE file for more info.