Reputation: 31
I have tried the following code to find out the last visible index path from collectionview but visible cells keeps changing and i am unable to find the last visible item.
for cell: UICollectionViewCell in collView.visibleCells {
// indexPath = collView.indexPathForCell(cell)!
var visibleRect = CGRect()
visibleRect.origin = collView.contentOffset
visibleRect.size = collView.bounds.size
let visiblePoint = CGPoint(x: visibleRect.width, y: visibleRect.height)
if let indexPath = collView.indexPathForItem(at: visiblePoint) //If let is
{
return indexPath
} else {
return IndexPath(row: NSNotFound, section: 0)
}
}
output
"<NSIndexPath: 0x17422c680> {length = 2, path = 0 - 4}",
"<NSIndexPath: 0x17403e0c0> {length = 2, path = 0 - 6}",
"<NSIndexPath: 0x1742261c0> {length = 2, path = 0 - 10}",
"<NSIndexPath: 0x17422adc0> {length = 2, path = 0 - 1}",
"<NSIndexPath: 0x1742205e0> {length = 2, path = 0 - 3}",
"<NSIndexPath: 0x17422a1a0> {length = 2, path = 0 - 7}",
"<NSIndexPath: 0x174227080> {length = 2, path = 0 - 9}",
"<NSIndexPath: 0x174229b40> {length = 2, path = 0 - 0}"
Upvotes: 1
Views: 4814
Reputation: 24341
You can use indexPathsForVisibleItems
to get an array of indexPaths of visible items in a UICollectionView
.
var indexPathsForVisibleItems: [IndexPath] { get }
The value of this property is an unsorted array of IndexPath objects, each of which corresponds to a visible cell in the collection view. This array does not include any supplementary views that are currently visible. If there are no visible items, the value of this property is an empty array.
Like in photos app as you specified, you will get multilple elements of IndexPath
in the array since more than 1 elements are visible at a particular instant.
Also, I don't understand what do you mean by last visible index. Please make it more clear for any further help.
Edit:
Example: I have created a UICollectionView with 30 cells and 1 section in it. For the below screen:
I have used the below lines of code:
let arrayOfVisibleItems = collectionView.indexPathsForVisibleItems.sorted()
let lastIndexPath = arrayOfVisibleItems.last
print("Array: ", arrayOfVisibleItems)
print("Last IndexPath: ", lastIndexPath)
Output:
Array: [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [0, 10], [0, 11], [0, 12], [0, 13], [0, 14], [0, 15], [0, 16], [0, 17], [0, 18], [0, 19], [0, 20]]
Last IndexPath: Optional([0, 20])
Upvotes: 2