實際開發(fā)中我們可以使用第三方實現(xiàn)無限輪播頭,但是一般都會有很多冗余的代碼。有時輪播圖中還可能對樣式要其他要求,索性步入封裝一個自己的無限輪播圖。下面介紹一下基于UICollectionView封裝的一個實用的輪播圖。源代碼鏈接:https://github.com/ZhengYaWei1992/ZWCycleView
效果圖
直接看如下的三十行核心代碼即可。cycleModels中放置的是輪播圖相關(guān)的圖像和文字信息。這里要注意在collectionView開始拖動的時候,銷毀定時器,在結(jié)束拖動的時候要創(chuàng)建定時器。不能通過[NSDate distantFuture]和[NSDate distancePast]控制定時器的開關(guān),應該是銷毀和創(chuàng)建,否則會有Bug。
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
/*********無限輪播關(guān)鍵點1****************/
return self.cycleModels.count * 10000;
}
- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
ZWCycleCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZWCycleCollectionCell" forIndexPath:indexPath];
/*********無限輪播關(guān)鍵點2****************/
//實際使用的時候用SDWebImage設(shè)置一下就可以
cell.myImageView.image = [UIImage imageNamed:self.cycleModels[indexPath.row % self.cycleModels.count].imageUrl];
cell.label.text =self.cycleModels[indexPath.row % self.cycleModels.count].des;
return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
// 1.獲取滾動的偏移量
CGFloat offsetX = scrollView.contentOffset.x + scrollView.frame.size.width * 0.5;
// 2.計算pageControl的currentIndex
/*********無限輪播關(guān)鍵點3****************/
self.pageControl.currentPage = (int)(offsetX/scrollView.frame.size.width) % (_cycleModels.count);
}
//開始拖動的時候銷毀定時器,結(jié)束拖動時開啟定時器。使用[NSDate distantFuture]和[NSDate distancePast]會有Bug
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
[self removeTimer];
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
[self addTimer];
}
- (void)onTimer:(NSTimer *)timer{
// 1.獲取滾動的偏移量
CGFloat currentOffsetX = self.collectionView.contentOffset.x;
CGFloat offsetX = currentOffsetX + self.collectionView.frame.size.width;
// 2.滾動該位置
[self.collectionView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}
-(void)addTimer{
_timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];
}
- (void)removeTimer{
[_timer invalidate];
_timer = nil;
}