本文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];
}
//確保定時器不出錯
以上呢就是輪播的簡單的實現,博主呢主要目的是給敢興趣的朋友提一個主要思路,供大家參考,當然這個類優化的空間很大,可擴展的空間也很大,有好的建議的伙伴可以盡管留言。