自定义控件首页投稿(暂停使用,暂停投稿)程序员

ios一个简单易用的轮播图的封装

2016-06-07  本文已影响1153人  mark666
效果图

本文gitoschia的地址

https://git.oschina.net/mark6/scrollLoop.git

本文gitHub地址

https://github.com/markdashi/scrollLoop

上一周在简书首页投稿看到了很多关于轮播图的文章,每一篇我都点进去看了一下,很可惜我看到的都是基于ScrollView的封装,好一点的会考虑到复用,就是放3个imageView来实现的图片的轮播,加上定时器。我很不理解的是,既然能考虑到复用的朋友为什么没有考虑到UICollecionView呢?好吧,我暂且相信你对UICollecionView不太熟悉,现在我将自己的思路及实现分享一下,供有兴趣的朋友参考一下。
首先我说一下UICollecionView的优点
1.首先不需要考虑复用,在整个过程中只会创建两个cell.
2.性能高,通用性强。

其次说一下实现的主要思路,
继承UIView定义一个scrollLoopView类,将UICollecionView添加到整个类subViews,定义数据源为传进来数组 * 10,开始定义collectionView为其中心位置,当滑动index超过数据源count时让它又从中心开始。当然这只是一个简单的思路,中间会有很多小细节处理,具体看代码。

#import <UIKit/UIKit.h>


@class scrollLoopView;
@protocol scrollLoopViewDelegate <NSObject>

@optional

- (void)scrollLoopView:(scrollLoopView *)scrollLoopView didSelectItemAtIndex:(int)index;


@end

@class scrollLoopViewDelegate;
@interface scrollLoopView : UIView

@property (nonatomic, strong) NSArray *images;
@property (nonatomic, weak) id<scrollLoopViewDelegate>delegate;
@end

在其initWithFrame写相应的配置

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self initsConfig];
        
    }
    
    
    return self;
}
/**
 *  配置基本框架
 */
- (void)initsConfig
{

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayout = layout;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor clearColor];
    collectionView.delegate  = self;
    collectionView.dataSource = self;
    collectionView.pagingEnabled = YES;
    collectionView.showsHorizontalScrollIndicator = NO;
    [collectionView registerNib:[UINib nibWithNibName:@"MyCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:identify];
    _collectionView = collectionView;
    [self addSubview:collectionView];
    
    UIPageControl *pageControl = [[UIPageControl alloc] init];
    _pageControl = pageControl;
    
    [self addSubview:pageControl];
    

}

这里一定要注意的是,在layoutSubView中,定义_flowLayout.itemSize尺寸,否则会报错。

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    _flowLayout.itemSize = self.frame.size;
    _collectionView.frame = self.bounds;
    
//这里是为了collection起始位置居中,而animated一定为NO,否则你会遇到你不想要效果
    if (_collectionView.contentOffset.x == 0 && _totalImageCount) {
        
        int tarIndex = _totalImageCount * 0.5;
        
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:tarIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    
  //_pageControl 的frame是相对固定的
    _pageControl.frame = CGRectMake((self.frame.size.width - 100)/2, self.frame.size.height - 30, 100, 20);
 
}

实现自动轮播少不了的是定时器NSTimer

- (void)setupTimer{

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:NSTimeIntervalDefault target:self selector:@selector(AutoScroll) userInfo:nil repeats:YES];
    _timer = timer;
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

}
- (void)AutoScroll
{
    
    int currentIndex = [self currentIndex];

    int targetIndex = currentIndex + 1;
    if (targetIndex >= _totalImageCount) {
        
        targetIndex = _totalImageCount * 0.5;
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        return;
    }

    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];

}
//当前第几页
- (int)currentIndex{

    if (_collectionView.frame.size.width == 0) {
        return 0;
    }
    int index = 0;
    
    index = (_collectionView.contentOffset.x + _flowLayout.itemSize.width * 0.5) /_flowLayout.itemSize.width;

    return index;
}

而定时器在哪里添加呢???有心的朋友可以不往下看,自己独立思考一下。

- (void)setImages:(NSArray *)images
{
    _images = images;
    _totalImageCount =  _images.count *10;
    if (images.count != 1) {
        [self setupTimer];
        _pageControl.numberOfPages = images.count;
    }

    [_collectionView reloadData];
}
//当设置数据源的时候,只要传进来的数据不为空,就设置定时器

接下来最最要的UICollectionView的代理方法

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _totalImageCount;
}

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

    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    
    long index = indexPath.item % self.images.count;
        
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:self.images[index]]];
    cell.label.text = [NSString stringWithFormat:@"%zd",index];
    
    return cell;
}

大家看代码,可以发现上面主要的加载的是网络图片,当然你可以判断传进来数组中字符串的类型,如果是本地,就采用imageNamed方法来加载

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

    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    
    long index = indexPath.item % self.images.count;
     cell.label.text = [NSString stringWithFormat:@"%zd",index];
    if (![self.images[index] hasPrefix:@"http"]) {
        cell.imageView.image =[UIImage imageNamed:self.images[index]];
        return cell;
    }
    
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:self.images[index]]];
   
    
    return cell;
}

点击的相应事件如下处理

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    if ([self.delegate respondsToSelector:@selector(scrollLoopView:didSelectItemAtIndex:)]) {
        
        [self.delegate scrollLoopView:self didSelectItemAtIndex:(int)indexPath.item % self.images.count];
    }
    
}

pageControl联动

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int index = [self currentIndex];
    _pageControl.currentPage = index % self.images.count;
    

}

这样呢我们这个类就简单的封装好了,使用起来更加简单,那个类使用,导入头文件

 scrollLoopView *loop = [[scrollLoopView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, 300)];
 loop.delegate = self;
loop.images =@[     @"http://web.img.chuanke.com/fragment/9d595bc8fb5bf049ce3db527ede08abc.jpg",
                    @"http://web.img.chuanke.com/fragment/d662adfaebdc9aa3dac4b04299aa48e1.jpg",
                    @"http://web.img.chuanke.com/fragment/8003092be7e6cc3222c760c89e74a20d.jpg",
                    ];
[self.view addsubView:loop];

优化部分

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self invalidateTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self setupTimer];
}
//确保定时器不出错

以上呢就是轮播的简单的实现,博主呢主要目的是给敢兴趣的朋友提一个主要思路,供大家参考,当然这个类优化的空间很大,可扩展的空间也很大,有好的建议的伙伴可以尽管留言。

上一篇 下一篇

猜你喜欢

热点阅读