您的位置:首页 > 其它

图片轮播器的两种实现方式(ScrollView与collectionView)

2015-11-11 18:59 459 查看
<span style="font-size:18px;color:#FF0000;">ScrollView实现图片轮播:</span>
ViewController.m

**********************头文件部分*************************

<span style="font-size:14px;">#import "ViewController.h"
#define kImageCount 5
#define kScrollViewSize (_scrollView.frame.size)</span>

**********************声明部分*************************

<span style="font-size:14px;">@interface ViewController ()<UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;

@property (nonatomic, strong) NSTimer *timer;

@end</span>
<span style="font-size:14px;">@implementation ViewController
<span style="color:#FF0000;">#pragma mark - 加载完视图调用</span>
- (void)viewDidLoad {
[super viewDidLoad];

[self setupUI];
}
<span style="color:#FF0000;">#pragma mark - 设置UI界面</span>
- (void)setupUI {

[self setupScrollView];

[self setupPageControl];

[self startTimer];
}
<span style="color:#FF0000;">#pragma mark - 设置scrollView</span>
- (void)setupScrollView {

// 设置代理
_scrollView.delegate = self;

// scrollView的size
CGSize scrollViewSize = _scrollView.frame.size;

for (int i = 0; i < kImageCount; i++) {

// 计算x的坐标
CGFloat imageViewX = i * scrollViewSize.width;

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(imageViewX, 0, scrollViewSize.width, scrollViewSize.height)];

// 拼接图片名称
NSString *imageName = [NSString stringWithFormat:@"img_%02d",i + 1];

// 设置图片
imageView.image = [UIImage imageNamed:imageName];

[_scrollView addSubview:imageView];
}

// scrollView的 contentSize
_scrollView.contentSize = CGSizeMake(kImageCount * scrollViewSize.width, 0);

// 隐藏水平方向上的 指示器
_scrollView.showsHorizontalScrollIndicator = NO;

// pageEnabled 分页效果
_scrollView.pagingEnabled = YES;

}
<span style="color:#FF0000;">#pragma mark - 设置PageControl</span>
- (void)setupPageControl {
// 设置有多少页
_pageControl.numberOfPages = kImageCount;

// 设置当前页
_pageControl.currentPage = 0;

// 设置页码指示器的颜色
_pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];

// 设置当前页码指示器的颜色
_pageControl.currentPageIndicatorTintColor = [UIColor redColor];

// 关闭用户交互
_pageControl.userInteractionEnabled = NO;
}
<span style="color:#FF0000;">#pragma mark - 设置定时器  重复的去调用target 的 changePage 这个方法</span>
- (void)startTimer {
_timer = [NSTimer scheduledTimerWithTimeInterval:1   // 间隔
target:self  // 控制器
selector:@selector(changePage)  // 调用的方法
userInfo:nil  // 传递的参数, 如果上面方法需要参数, 就在这里传递
repeats:YES]; // 是否重复

// fire , 立即执行, 不会 等待  interval 结束
//    [_timer fire];

// 取出主循环
NSRunLoop *mainLoop = [NSRunLoop mainRunLoop];

// 修改timer 的优先级
[mainLoop addTimer:_timer forMode:NSRunLoopCommonModes];
}
/*
想要知道当前滚动到第几张图片
用  _scrollView.contentOffset.x / _scrollView.frame.size.width

*/
<span style="color:#FF0000;">#pragma mark - 当scrollView滚动即将离开当前页面是调用</span>
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
// 计算当前是第几张图片
NSInteger currentPage = scrollView.contentOffset.x / scrollView.frame.size.width;

// 设置 pagecontorl的 当前页码
_pageControl.currentPage = currentPage;
}

// 点击一次按钮, 跳到下一张图片
// pageControl 的currentPage 不能超过 numberOfPages

- (void)changePage {

NSInteger currentPage = _pageControl.currentPage;
CGPoint offset = _scrollView.contentOffset;
// currentPage 最大为4
if (currentPage >= _pageControl.numberOfPages - 1) {
// 不能再继续向后滚动

currentPage = 0;
offset = CGPointZero;
} else {
currentPage++;
offset.x += kScrollViewSize.width;
}

_pageControl.currentPage = currentPage;

[_scrollView setContentOffset:offset animated:YES];
}
/**
1. 什么时候关闭计时器?
手指头碰到scrollView的时候, 就把计时器关闭
scrollViewWillBeginDragging:

2. 什么时候开启计时器?
手指头离开屏幕的时候, 开启计时器
scrollViewDidEndDragging

*/
<span style="color:#FF0000;">#pragma mark - 开始拖动的时候</span>
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
// 关闭计时器 , 如果调用invalidate , 这个计时器就没了, 如果重新开启, 就必须创建新的
[_timer invalidate];
}
<span style="color:#FF0000;">#pragma mark - 结束拖动的时候调用</span>
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
// 开启计时器

//    [_timer fire];
[self startTimer];
}

@end
</span>

collectionView实现图片轮播:
ViewController.m

**********************头文件部分 *************************

<span style="font-size:14px;">#import "ViewController.h"
#import "CollectionViewCell.h"
#define kWIDTH [UIScreen mainScreen].bounds.size.width

</span>


**********************声明部分*************************

<span style="font-size:14px;">@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property(nonatomic ,strong) NSMutableArray *images;

@property(nonatomic ,strong) UICollectionView *collectionView;

@property(nonatomic ,strong) NSIndexPath *indexpath;

@property(nonatomic ,assign) NSInteger index;

@property(nonatomic ,strong) NSTimer *timer;

@end

</span>


**********************实现部分*************************

<span style="font-size:14px;">@implementation ViewController
<span style="color:#FF0000;">#pragma mark - 懒加载</span>
-(NSMutableArray *)images
{
if (!_images) {
_images = [NSMutableArray array];

for (int i = 1; i < 11; i++) {

NSString *path = [NSString stringWithFormat:@"%02d.jpg",i];

[_images addObject:path];

}
}

return _images;
}
<span style="color:#FF0000;">#pragma mark - 加载完视图调用</span>
- (void)viewDidLoad {
[super viewDidLoad];
//初始化点击位置
self.index = 1000;

UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//设置layout属性
layout.itemSize = CGSizeMake(kWIDTH, 300);
layout.minimumInteritemSpacing = 0;
layout.minimumLineSpacing = 0;
// 滚动方向
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 50, kWIDTH , 300) collectionViewLayout:layout];

collectionView.backgroundColor = [UIColor greenColor];

[collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"CollectionViewCell"];
//此句代码作用是为了后面使用左准备
self.collectionView = collectionView;

// 设置分页
collectionView.pagingEnabled = YES;
//设置代理
collectionView.dataSource = self;
collectionView.delegate = self;
//获取点击位置
NSIndexPath *indexpath = [NSIndexPath indexPathForItem:self.index inSection:0];
//此句代码作用是为了后面使用左准备
self.indexpath = indexpath;

[collectionView scrollToItemAtIndexPath:indexpath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
//添加 collectionView
[self.view addSubview:collectionView];

[self addTimer];
}
<span style="color:#FF0000;">#pragma mark - 添加定时器</span>
- (void)addTimer
{
NSTimer *timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(scollImage) userInfo:nil repeats:YES];

self.timer = timer;
//将定时器加入运行循环当中
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
<span style="color:#FF0000;">#pragma mark - 删除定时器</span>
- (void)deleteTimer
{    //使定时器无效
[self.timer invalidate];

self.timer = nil;
}
<span style="color:#FF0000;">#pragma mark - 图片滑动</span>
-(void)scollImage
{
self.index ++;

NSLog(@"-------- %ld",self.index);

NSIndexPath *indexpath = [NSIndexPath indexPathForItem:self.index inSection:0];
//滚动到相应位置
[self.collectionView scrollToItemAtIndexPath:indexpath atScrollPosition:0 animated:YES];
}
<span style="color:#FF0000;">#pragma mark - 返回多少组</span>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
<span style="color:#FF0000;">#pragma mark - 返回多少个 item</span>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 1000*1000;
}
<span style="color:#FF0000;">#pragma mark - 返回怎样的 CollectionViewCell</span>
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewCell" forIndexPath:indexPath];

cell.backgroundColor = [UIColor redColor];
//获取图片
NSString *imageUrl = self.images[indexPath.item%10];

UIImage *image = [UIImage imageNamed:imageUrl];

cell.image = image;

return cell;

}
<span style="color:#FF0000;">#pragma mark - 开始滚动,并停止定时器</span>
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
[self deleteTimer];
}
<span style="color:#FF0000;">#pragma mark - 减速滚动直到下个页面时调用</span>
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

// 页面的偏移量,如果是0表示页面没有变化
NSInteger offset = (scrollView.contentOffset.x / scrollView.bounds.size.width);

self.index = offset;
NSLog(@"==> %zd", offset);

[self addTimer];
}

@end</span>


CollectionViewCell.h   文件

<span style="font-size:14px;">#import <UIKit/UIKit.h>

@interface CollectionViewCell : UICollectionViewCell

@property(nonatomic ,strong) UIImage *image;

@property(nonatomic ,strong) UIImageView *imageView;
</span>

@end
CollectionViewCell.m
**********************头文件部分*************************

<span style="font-size:14px;">#import "CollectionViewCell.h"
#define kWIDTH [UIScreen mainScreen].bounds.size.width</span>
**********************实现部分*************************

<span style="color:#FF0000;">#pragma - mark 一次性初始化设置 </span><pre name="code" class="objc"><span style="font-size:14px;color:#FF0000;">CollectionViewCell</span>

<span style="font-size:14px;">@implementation CollectionViewCell

-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, 300)];

self.imageView = imageView;

imageView.image = self.image;

[self.contentView addSubview:imageView];

return self;
}
<span style="color:#FF0000;">#pragma - mark 设置图片</span>
-(void)setImage:(UIImage *)image
{
_image = image;

self.imageView.image = image;
}
@end</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息