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
importUICollectionViewParallaxCellIn your custom UICollectionViewCell class, inherit the UICollectionViewParallaxCell class.
classCustomParallaxCell: UICollectionViewParallaxCell{...}Within that class declare a UIImage
classCustomParallaxCell: UICollectionViewParallaxCell{varbackgroundImage : UIImageView?{didSet{guardletimageView=backgroundImageelse{return}imageView.contentMode=.scaleAspectFillsetupbackgroundParallax(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:
funccollectionView(_collectionView: UICollectionView,cellForItemAtindexPath: IndexPath) -> UICollectionViewCell{letcell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId,for: indexPath)as!CustomParallaxCellcell.paddingOffset=150 // declares the offset intensity of parallax cell.backgroundImage = // passthroughtheUIImageViewobjecttoinstantiatethesetupbackgroundParallaxfunctioninthedidSetletbounds=collectionView.bounds//variableforthecollectionViewboundscell.parallaxOffset(collectionViewBounds: bounds,scrollDirecton: .vertical)//instantiatetheinitalboundsofthecollectionviewreturncell}Next call the scrollViewDidScroll function in the class with your UICollectionView. Declare the following:
funcscrollViewDidScroll(_scrollView: UIScrollView){letcells=collectionView.visibleCellsas![CustomParallaxCell]letbounds=collectionView.boundsforcellincells{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.
