Unlimited image carousel-the simplest way to achieve unlimited image carousel
In collectionView, only three cells are displayed as the second cell.
-(UICollectionViewCell *) collectionView :( UICollectionView *) collectionView cellForItemAtIndexPath :( NSIndexPath *) indexPath {
CycleViewCell * cell = [collectionViewdequeueReusableCellWithReuseIdentifier: @ "Cell" forIndexPath: indexPath];
// IndexPath. item-1 is equivalent to adding 1 to the left of index and one to the right
// IndexPath. item-1. If you move left, the third cell 2-1 will be displayed, which is equivalent to self. currentIndex + 1.
// IndexPath. item-1. If you move the value to the right, the first cell 0-1 will be displayed, which is equivalent to self. currentIndex-1.
NSInteger index = (self. currentIndex + indexPath. item-1 + self. imageURLs. count) % self. imageURLs. count;
Cell. imageURL = self. imageURLs [index];
Return cell;
}
// Method called after the rolling view stops rolling completely
-(Void) scrollViewDidEndDecelerating :( UIScrollView *) scrollView {
// 1. Based on the contentOffset, you can determine the page to stay on.
Int page = scrollView. contentOffset. x/scrollView. bounds. size. width;
NSLog (@ "page % d", page );
// 2. If it is page 0th, self. currentIndex-1, if it is page 2nd, self. currentIndex + 1;
Self. currentIndex = (self. currentIndex + page-1 + self. imageURLs. count) % self. imageURLs. count;
// 3. Let the collection scroll to display the first page
NSIndexPath * indexPath = [NSIndexPathindexPathForItem: 1 inSection: 0];
[Self. collectionViewscrollToItemAtIndexPath: indexPathatScrollPosition: UICollectionViewScrollPositionCenteredHorizontallyanimated: NO];
}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.