Skip to content

Instantly share code, notes, and snippets.

@jamesrochabrun
Created October 9, 2018 16:03
Show Gist options
  • Save jamesrochabrun/428fea1d14468ba5863f33a17a323d9b to your computer and use it in GitHub Desktop.
Save jamesrochabrun/428fea1d14468ba5863f33a17a323d9b to your computer and use it in GitHub Desktop.
func fadeHorizontalEdges(in collectionView: UICollectionView, modifier: CGFloat) {
let visibleCells = collectionView.visibleCells
guard !visibleCells.isEmpty else { return }
let firstCell = visibleCells.first!
let lastCell = visibleCells.last!
visibleCells.forEach { $0.alpha = 1 }
let cellWidth = firstCell.frame.width - 1 // 1 needs to change for the minimumline spacing
let collectionViewLeftEdgePosition = collectionView.frame.origin.x
let collectionViewRightEdgePosition = collectionView.frame.origin.x + collectionView.frame.size.width
let indexPath = collectionView.indexPath(for: firstCell)!
let theAttributes:UICollectionViewLayoutAttributes! = collectionView.layoutAttributesForItem(at: indexPath)
let firstCellPositionInCollectionView: CGRect = collectionView.convert(theAttributes.frame, to: collectionView.superview)
let indexPathLast = collectionView.indexPath(for: lastCell)!
let theAttributeLast: UICollectionViewLayoutAttributes! = collectionView.layoutAttributesForItem(at: indexPathLast)
let lastCellPositionInCollectionView: CGRect = collectionView.convert(theAttributeLast.frame, to: collectionView.superview)
let firstCellPosition: CGFloat = collectionView.convert(firstCellPositionInCollectionView, to: collectionView.superview).origin.x
let lastCellPosition: CGFloat = collectionView.convert(lastCellPositionInCollectionView, to: collectionView.superview).origin.x + cellWidth
let firstCellOpacity = 1.0 - (((collectionViewLeftEdgePosition - firstCellPosition) / cellWidth) * modifier)
let lastCellOpacity = 1.0 - (((lastCellPosition - collectionViewRightEdgePosition) / cellWidth) * modifier)
firstCell.contentView.alpha = firstCellOpacity
lastCell.contentView.alpha = lastCellOpacity
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment