ios一個簡單易用的輪播圖的封裝

效果圖

本文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];
}
//確保定時器不出錯

以上呢就是輪播的簡單的實現,博主呢主要目的是給敢興趣的朋友提一個主要思路,供大家參考,當然這個類優化的空間很大,可擴展的空間也很大,有好的建議的伙伴可以盡管留言。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,813評論 25 708
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,180評論 4 61
  • 下雨了,電線上的水珠像是跳動的音符,敲響所有孤單,你回家沒有撐傘。 十月秋涼,季節的溫度被南飛的翅影帶走,阿嬤早早...
    何子初閱讀 232評論 0 2
  • 昨晚做了一小段夢,夢見了初中的班長,她成了我的同桌。我換座位搬過去時周圍同學都投來了異樣的眼光,但我心里有些小小的...
    終究是過去閱讀 84評論 0 1
  • 總是感嘆自己非常輕松的就把自己的情緒控制住了!其實只是不想麻煩朋友,不想去傾訴,一般都是時過境遷之后,拿出...
    我是泡泡啊閱讀 209評論 0 0