第一
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
SDCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
long itemIndex = indexPath.item % self.imagePathsGroup.count;
NSString *imagePath = self.imagePathsGroup[itemIndex];
}
....
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return N;
}
long itemIndex = indexPath.item % self.imagePathsGroup.count;
indexPath.item代表cell的索引0,1,2,3....N-1
但是图片只有5张,怎么让这些Cell来显示这五张图片,
只有用取余的方法,从图片数组中取出图片
第二
定时器,自动滚动的方法里面怎么处理
- (void)automaticScroll
{
if (0 == _totalItemsCount) return;
int currentIndex = [self currentIndex];
int targetIndex = currentIndex + 1;
if (targetIndex >= _totalItemsCount) {
if (self.infiniteLoop) {
targetIndex = _totalItemsCount * 0.5;
[_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
}
return;
}
[_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
}
- (int)currentIndex
{
if (_mainView.sd_width == 0 || _mainView.sd_height == 0) {
return 0;
}
int index = 0;
if (_flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
index = (_mainView.contentOffset.x + _flowLayout.itemSize.width * 0.5) / _flowLayout.itemSize.width;
} else {
index = (_mainView.contentOffset.y + _flowLayout.itemSize.height * 0.5) / _flowLayout.itemSize.height;
}
return MAX(0, index);
}
参数currentIndex和参数targetIndex
通过- (int)currentIndex可以看出,
currentIndex就是indexPath.item也就是,当前UICollectionViewCell的索引
targetIndex 就是滚动到下一个的UICollectionViewCell
if (targetIndex >= _totalItemsCount) {
就代表已经达到了numberOfItemsInSection的总个数,需要重新计算targetIndex,
[_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
代表从CollectionView 从当前currentIndex滚动到targetIndex索引
//定时器的作用就是利用 scrollToItemAtIndexPath 这个函数来滚动到下一页,现在缺少要滚动到那一页
//也就是indexPath.row
//现在主要计算就是这个索引
//现在根据scrollView的contentOffset.x来计算,但是这个值的变动,主要是调动scrollViewDidScroll
//而scrollViewDidScroll 调动的原因,是因为scrollView滚动,
//scrollView滚动的话,则需要调动scrollToItemAtIndexPath这个函数
//也就是说,在定时器,开始之前,需要首先调动,scrollToItemAtIndexPath, 关键是在哪触发调动?
//需要计算目标索引和当前索引
//
代码来源: