Created
September 23, 2016 04:47
-
-
Save sakiwei/b6b01e8c940b3d1bbbf65013ae48cab3 to your computer and use it in GitHub Desktop.
Get UICollectionViewCell viewport percentage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
extension UICollectionView { | |
var cellOffsetForVisibleItems: [IndexPath: CGFloat] { | |
let result = self.indexPathsForVisibleItems | |
.map { indexPath in | |
[indexPath: UICollectionView.cellOffset(with: self, at: indexPath)] | |
} | |
.reduce([IndexPath: CGFloat]()) { result, map in | |
var newResult = result | |
newResult += map | |
return newResult | |
} | |
return result | |
} | |
static func cellOffset(with collectionView: UICollectionView, at indexPath: IndexPath) -> CGFloat { | |
if let cell = collectionView.cellForItem(at: indexPath) { | |
return cellOffset(with: collectionView, for: cell) | |
} | |
return 0.0 | |
} | |
static func cellOffset(with collectionView: UICollectionView, for cell: UICollectionViewCell) -> CGFloat { | |
let cellFrame = cell.frame | |
let cellFrameInTable = collectionView.convert(cellFrame, to: collectionView.superview) | |
let cellOffset = cellFrameInTable.origin.y + cellFrameInTable.size.height | |
let tableHeight = collectionView.bounds.size.height + cellFrameInTable.size.height | |
let cellOffsetFactor = cellOffset / tableHeight | |
return cellOffsetFactor | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment