天天看點

圖檔無限輪播-最簡單的實作方法

collectionView中隻有三個cell 每次顯示的都是第二個cell

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    CycleViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    //indexPath.item - 1 相當于index左移加1  右移減一

   //indexPath.item - 1 如果左移就相當于要顯示第三個cell 2-1  ,相當于self.currentIndex + 1

   //indexPath.item - 1 如果右移就相當于要顯示第一個cell 0-1  ,相當于self.currentIndex - 1

    NSInteger index = (self.currentIndex + indexPath.item - 1 + self.imageURLs.count) % self.imageURLs.count;

    cell.imageURL = self.imageURLs[index];

    return cell;

}

// 在滾動視圖完全停止滾動後會調用的方法

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    // 1. 根據contentOffset可以判斷出停留住的頁面

    int page = scrollView.contentOffset.x / scrollView.bounds.size.width;

    NSLog(@"第 %d 頁", page);

    // 2. 如果是第0頁,self.currentIndex - 1,如果是第2頁,self.currentIndex +1;

    self.currentIndex = (self.currentIndex + page - 1 + self.imageURLs.count) % self.imageURLs.count;

    // 3. 讓collection滾動會第一個頁面

    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:1 inSection:0];

    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];

}

繼續閱讀