Skip to content

Commit 4bd0209

Browse files
authored
Update InfiniteCollectionView.swift
~ Enhanced the implementation to correct the index.
1 parent 6fcd6a5 commit 4bd0209

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

InfiniteCollectionView/InfiniteCollectionView.swift

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,27 @@ open class InfiniteCollectionView: UICollectionView {
5050
open func rotate(_ notification: Notification) {
5151
setContentOffset(CGPoint(x: CGFloat(pageIndex + indexOffset) * itemWidth, y: contentOffset.y), animated: false)
5252
}
53+
5354
open override func selectItem(at indexPath: IndexPath?, animated: Bool, scrollPosition: UICollectionViewScrollPosition) {
54-
let updatedIndexPath = IndexPath(row: correctedIndex(indexPath!.item + indexOffset), section: 0);
55-
super.selectItem(at: updatedIndexPath, animated: animated, scrollPosition: scrollPosition);
55+
56+
// Correct the input IndexPath
57+
let correctedIndexPath = IndexPath(row: correctedIndex(indexPath!.item + indexOffset), section: 0);
58+
59+
// Get the currently visible cell(s) - assumes a cell is visible
60+
guard let visibleCell = self.visibleCells.first else{
61+
return; // Nothing to select...
62+
}
63+
// Index path of the cell - does not consider multiple cells on the screen at the same time
64+
var visibleIndexPath : IndexPath! = self.indexPath(for: visibleCell);
65+
66+
let testIndexPath = IndexPath(row: correctedIndex(visibleIndexPath!.item), section: 0);
67+
68+
guard correctedIndexPath != testIndexPath else{
69+
return; // Do not re-select the same cell
70+
}
71+
72+
// Call supercase to select the correct IndexPath
73+
super.selectItem(at: correctedIndexPath, animated: animated, scrollPosition: scrollPosition);
5674
}
5775
}
5876

0 commit comments

Comments
 (0)