第一步:
// 程序一開始就滾動到第二個cell
// 滾動的前提是已經有cell數據了(所以不要在數據還沒有加載就滾動)
NSIndexPath *idxPath = [NSIndexPath indexPathForItem:1 inSection:0];
[self.collectionView scrollToItemAtIndexPath:idxPath atScrollPosition:0 animated:NO];
第二步:
// 增加一個屬性,表示當前圖片的索引
@property (nonatomic,assign) NSInteger currentIndex;
// 停止滾動(減速)的時候調用該方法
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//獲取滾動了多少個cell大小(因爲滾動前cell就偏移了一個cell的距離,所以實際cell滾動的大小要減去一)
NSInteger offset = scrollView.contentOffset.x/ scrollView.bounds.size.width - 1;
//當前(上一個當前)圖片的索引加上滾動的大小就是滾動後圖片的索引(也就是最新的currentIndex)
self.currentIndex = (self.currentIndex + offset + self.headlines.count) % self.headlines.count;
// cell.headline = self.headlines[index];這段代碼的內部是異步執行的(加載網絡圖片),所以把下面的代碼放在主隊列中,等主線程上的代碼執行完畢之後再執行.
dispatch_async(dispatch_get_main_queue(), ^{
// 當滾動結束後,讓第一個cell再偷偷的(無動畫)滾回界面
// 所以還會自動執行返回cell的方法
NSIndexPath *idxPath = [NSIndexPath indexPathForItem:1 inSection:0];
[self.collectionView scrollToItemAtIndexPath:idxPath atScrollPosition:0 animated:NO];
});
}
第三步:
// 要顯示多少個cell,當前方法將被調用多少次(所以當前程序第一次啓動時也要調用一次)
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionViewcellForItemAtIndexPath:(NSIndexPath*)indexPath {
HMHeadlineCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"headline" forIndexPath:indexPath];
//(當然在程序剛進來的時候,item爲1)
//1. 這裏不能使用self.currentIndex表示下一個圖片的索引,否則會出現拖動的時候下一張圖片和當前圖片相同.
//2. 當圖片一個一個滾動的時候,currentIndex在變化,下一個圖片不是在currentIndex的基礎上+1,就是在currentIndex的基礎上-1;而在圖片一個一個滾動的過程中,indexPath.item的值不是0就是2,如果給item-1的話,item-1的結果不是-1就是1,所以計算下一個圖片的索引可以使用 currentIndex + item - 1。
//3. 當圖片快速滾動的時候,currentIndex沒有發生變化,但是item值不會只是0或2了,它會隨着快速滾動圖片的個數而發生變化(遞增或者遞減),item-1的值也不會只是-1或者1了;但是注意,當我們快速滾動的時候,這個方法會被連續調用,所以item-1可能表示的是下一個圖片,也可能表示的是下下個圖片,所以使用currentIndex + item - 1也是可行的。
//4. 爲了在圖片滾動的時候不越界,所以加上self.headlines.count,再對self.headlines.count取餘
NSInteger index = (self.currentIndex + indexPath.item- 1 + self.headlines.count)% self.headlines.count;
cell.headline = nil;
//下一個模型數據賦給cell
cell.tag = index;
cell.headline = self.headlines[index];
return cell;
}