iOS 常见问题汇总

IOS开发-UICollection实现轮播图片自动循环滚动功能

2017-12-15  本文已影响568人  ZAREMYDREAM

无限轮播

先来一张预览


轮播.gif

要实现该功能主要就是解决以下几个问题:
1.collection的自动滚动。
2.图片滚动到开头和末尾是回到另一端重新开始的无缝连接。

self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(scrollImage) userInfo:nil repeats:YES];
#pragma mark - 定时器滚动collectionView
-(void)scrollImage{
    int page = (int)_collection.contentOffset.x / self.view.frame.size.width;
    
    page++;
    
    if (page < 6)
    {
        [_collection setContentOffset:CGPointMake(page * self.view.frame.size.width, 0) animated:YES];
        
    }

}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (cell == nil)
    {
        cell = [[UICollectionViewCell alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 300)];
    }
    else
    {
        while ([cell.contentView.subviews lastObject] != nil)
        {
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    
    //将第一张加到最后一个cell,将最后一张加载到最后一个cell
    NSInteger imageNum;
    switch (indexPath.row) {
        case 0:
            imageNum = 3;
            break;
            
        case 5:
            imageNum = 0;
            break;
            
        default:
            imageNum = indexPath.row - 1;
            break;
    }
    
    UIImageView *imgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"img_0%ld",(long)imageNum]]];
    
    imgV.frame = CGRectMake(0, 0, self.view.frame.size.width, 300);
    
    [cell addSubview:imgV];
    
    return cell;
}
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    if ([scrollView isEqual:_collection])
    {
        int page = (int)_collection.contentOffset.x / self.view.frame.size.width;
        
        if (page == 5)
        {
            //当到达最后一个cell时,自动回到第二个cell
            ![soogif1.gif](https://img.haomeiwen.com/i8715491/f686e65485114680.gif?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
//关闭动画效果,形成视觉上的不可见
            [_collection setContentOffset:CGPointMake(self.view.frame.size.width, 0) animated:NO];
            
            self.page.currentPage = 0;
        }
        else if (page == 0)
        {
            //当到达第一个cell时,自动跳转到倒数第二个cell
            //关闭动画效果,形成视觉上的不可见
            [_collection setContentOffset:CGPointMake(5 * self.view.frame.size.width, 0) animated:NO];
            
            self.page.currentPage = 3;
        }
        else
        {
            self.page.currentPage = page - 1;
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读