iOS 超简单无限轮播
2016-07-11 本文已影响867人
倚楼听风雨wing
无限轮播.gif
简介##
现在的公司项目基本上都会要求来一两个无限轮播,可是如何才能够把这个无限轮播写好了,看着挺简单的,加上一个定时器走你.我以前用ScrollView写过一个无限轮播,发现在只有两条数据的时候左右拖动是会有问题,并且逻辑还非常的复杂,今天就给大家分享一个简单的无限轮播方法.
毫无疑问,要想让图片自己不停的切换,需要使用到定时器,为了方便使用,我在这里给定时器写了一个分类.通过定时器的暂停和恢复来实现轮播图的暂停和恢复.
#import "NSTimer+addition.h"
@implementation NSTimer (addition)
/// 暂停
- (void)pause {
if (!self.isValid) return;
[self setFireDate:[NSDate distantFuture]];
}
/// 恢复
- (void)resume {
if (!self.isValid) return;
[self setFireDate:[NSDate date]];
}
/// 多少秒后恢复
- (void)resumeWithTimeInterval:(NSTimeInterval)time {
if (!self.isValid) return;
[self setFireDate:[NSDate dateWithTimeIntervalSinceNow:time]];
}
@end
要诀 使用UITableView
或者UICollectionView
来做无限轮播,然后设置在其代理方法返回有多少rows的时候返回一个巨大的数字.上面顶部的banner滚动条就是用UICollectionView
做的,接下来我会着重讲使用UICollectionView
的无限轮播做法,UITableView
类似.
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
// 在这里返回一个比较大的数字
return 5000000;
}
我的轮播视图WYLoopView.h
// 点击了轮播图的block
typedef void(^TapAction)(UIImage *image);
@interface WYLoopView : UIView
@property (nonatomic, strong) NSArray *dataSource;
- (instancetype)initWithFrame:(CGRect)frame tapAction:(TapAction)action;
// 恢复
- (void)resume;
// 暂停
- (void)pause;
@end
WYLoopView.m
我设置了当只有一个图的时候不让其滚动,最少两张图才可以滚动.
#import "WYLoopView.h"
#import "NSTimer+addition.h"
#import "UIImageView+WebCache.h"
#define INDEX indexPath.item % _dataSource.count
static NSString *const kReuseId = @"LoopCell";
static NSInteger const kMaxCount = 1000000;
static NSTimeInterval const kTimeInterval = 1.0;
//////////////////////////////////// WYLoopCell ////////////////////////
@interface WYLoopCell : UICollectionViewCell
@property (nonatomic, copy) NSString *url;
@end
@implementation WYLoopCell
{
UIImageView *_imageView;
}
- (void)setURL:(NSString *)url {
_url = url;
[_imageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"ic_home_banner_defult.png"]];
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self setupUI];
}
return self;
}
- (void)setupUI {
_imageView = [[UIImageView alloc] initWithFrame:self.contentView.bounds];
[self.contentView addSubview:_imageView];
}
@end
//////////////////////////////////// WYLoopView ////////////////////////
@interface WYLoopView ()<UICollectionViewDataSource, UICollectionViewDelegate>
@end
@implementation WYLoopView
{
UICollectionView *_collectionView;
UIPageControl *_pageControl;
NSTimer *_timer;
TapAction _action;
NSInteger _currentPage;
}
- (instancetype)initWithFrame:(CGRect)frame tapAction:(TapAction)action {
if (self = [super initWithFrame:frame]) {
_action = action;
[self initialTimer];
[self setupUI];
}
return self;
}
- (void)dealloc {
[_timer invalidate];
_timer = nil;
}
- (void)pause {
[_timer pause];
}
- (void)resume {
[_timer resumeWithTimeInterval:kTimeInterval];
}
#pragma mark - setter
- (void)setDataSource:(NSArray *)dataSource {
[_timer pause];
_dataSource = dataSource;
_pageControl.numberOfPages = _dataSource.count > 1 ?_dataSource.count:0;
[_collectionView reloadData];
_pageControl.currentPage = 0;
if (_dataSource.count < 2) return;
[_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_dataSource.count * 10 inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
_currentPage = _dataSource.count * 10;
[_timer resumeWithTimeInterval:kTimeInterval];
}
#pragma mark - NSTimer
- (void)initialTimer {
_timer = [NSTimer scheduledTimerWithTimeInterval:kTimeInterval target:self selector:@selector(nextPage:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
[_timer pause];
}
- (void)nextPage:(NSTimer *)timer {
if (_dataSource.count < 2) return;
[_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:++_currentPage inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
_pageControl.currentPage = _currentPage % _dataSource.count;
}
#pragma mark - setupUI
- (void)setupUI {
[self prepareCollectionView];
[self preparePageControl];
[self addSubview:_collectionView];
[self addSubview:_pageControl];
UIImageView *logoView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 26, 55, 25)];
logoView.image = [UIImage imageNamed:@"ic_home_logo"];
[self addSubview:logoView];
}
- (void)prepareCollectionView {
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.itemSize = self.bounds.size;
flowLayout.minimumInteritemSpacing = 0;
flowLayout.minimumLineSpacing = 0;
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
_collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
_collectionView.dataSource = self;
_collectionView.delegate = self;
_collectionView.pagingEnabled = YES;
_collectionView.showsHorizontalScrollIndicator = NO;
// 注册cell
[_collectionView registerClass:[WYLoopCell class] forCellWithReuseIdentifier:kReuseId];
}
- (void)preparePageControl {
_pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 100) * 0.5, self.bounds.size.height - 17, 100 , 5)];
_pageControl.numberOfPages = _dataSource.count;
// _pageControl.currentPageIndicatorTintColor = [UIColor greenColor];
// _pageControl.pageIndicatorTintColor = [UIColor orangeColor];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return _dataSource.count > 1 ? kMaxCount : _dataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
WYLoopCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kReuseId forIndexPath:indexPath];
cell.url = _dataSource[INDEX];
return cell;
}
#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
if (!_action) return;
_action(_dataSource[INDEX]);
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
_currentPage = scrollView.contentOffset.x / SCREEN_WIDTH;
_pageControl.currentPage = _currentPage % _dataSource.count;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
[_timer pause];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
[_timer resumeWithTimeInterval:kTimeInterval];
}
@end