简易轮播图的实现(前后各加一张假图的方式)
2016-04-25 16:00
246 查看
// 项目中轮播图的登场率还是很大的,之前有用到轮播三方 但看他源码的时候发现 创建了好多组数据 这无形中浪费了一部分内存
// 其实轮播图的实现也算是很简单的了 今天就带大家做一个简易的轮播图
// 实现功能:带定时器 可以手动拖拽 手动拖拽定时器停止 手动拖拽结束一定时间 定时器重新启动
// 创建一个UIView 子类JWCarouselFigureView
// JWCarouselFigureView.h
#import <UIKit/UIKit.h>
@interface JWCarouselFigureView : UIView
/*图片数组*/
@property(copy,nonatomic)NSArray *pics;
/*标题数组*/
@property(copy,nonatomic)NSArray *titles;
/*轮播时间间隔*/
@property(assign,nonatomic)NSInteger sec;
/*拖拽结束重新开启定时器间隔*/
@property(assign,nonatomic)NSInteger secNew;
/*点击回传*/
@property(copy,nonatomic)void(^CallBack)(NSInteger index);
@end
// JWCarouselFigureView.m具体实现
#import "JWCarouselFigureView.h"
#import "JWCollectionViewCell.h"
#define kWIDTH [UIScreen mainScreen].bounds.size.width
#define kSEC 3
@interface JWCarouselFigureView()<UICollectionViewDataSource,UICollectionViewDelegate>
@property(nonatomic,strong)UICollectionView *collectionView;
@property(assign,nonatomic,getter=isStart)BOOL start;// 判断定时器状态 防止多次创建
@property(weak,nonatomic)NSTimer *timer;
@end
@implementation JWCarouselFigureView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
#pragma - mark collectioView初始化
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
layout.itemSize = CGSizeMake(self.frame.size.width, self.frame.size.height);
layout.minimumInteritemSpacing = 0;
layout.minimumLineSpacing = 0;
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
collectionView.delegate = self;
collectionView.pagingEnabled = YES;
collectionView.dataSource = self;
self.collectionView = collectionView;
[collectionView registerNib:[UINib nibWithNibName:@"JWCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"JWCollectionViewCell"];
// 第一个出现的是第二个item也就是数据的第一条数据
collectionView.contentOffset = CGPointMake(frame.size.width, 0);
[self addSubview:collectionView];
// 初始化定时器
[self setUpTimer];
}
return self;
}
#pragma - collectionView协议方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
JWCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"JWCollectionViewCell" forIndexPath:indexPath];
return [self setDataForCell:cell IndexPath:indexPath];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.pics.count + 2;
}
#pragma - mark cell赋值
- (UICollectionViewCell *)setDataForCell:(JWCollectionViewCell *)cell IndexPath:(NSIndexPath *)indexPath
{
#pragma - mark 判断是第几个cell 第一个cell赋数组最后一个数据,最后一个cell赋值数组第一个数据
NSInteger count = self.pics.count;
if (indexPath.item == 0) {
cell.url = [self.pics lastObject];
cell.title = self.titles.count > 0 ? [self.titles lastObject]:nil;
cell.num = [NSString stringWithFormat:@"%ld/%ld",(unsigned long)self.pics.count,(unsigned long)self.pics.count];
} else if(indexPath.item == count + 1){
cell.url = [self.pics firstObject];
cell.title = self.titles.count > 0 ? [self.titles firstObject]:nil;
cell.num = [NSString stringWithFormat:@"1/%ld",(unsigned long)self.pics.count];
} else
{
cell.url = [self.pics objectAtIndex:indexPath.item - 1];
cell.title = self.titles.count > 0 ? [self.titles objectAtIndex:indexPath.item - 1]:nil;
cell.num = [NSString stringWithFormat:@"%ld/%ld",(long)indexPath.item,(unsigned long)self.pics.count];
}
return cell;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
NSInteger index = scrollView.contentOffset.x / kWIDTH;
#pragma - 手动滑动时候判断滑到第几张 执行相应的跳转
if (index == self.pics.count + 1) {
self.collectionView.contentOffset = CGPointMake(kWIDTH * 1, 0);
} else if(index == 0){
self.collectionView.contentOffset = CGPointMake(kWIDTH * self.pics.count, 0);
}
}
#pragma mark - 定时器创建方法
- (void)setUpTimer
{
if (!_start) {
NSInteger sec = self.sec > 0 ? self.sec : kSEC;
self.timer = [NSTimer timerWithTimeInterval:sec target:self selector:@selector(timerActionMethod) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
_start = !_start;
}
}
// 定时器关联方法
- (void)timerActionMethod
{
NSInteger index = self.collectionView.contentOffset.x / kWIDTH;
NSInteger pointX = 0;
if (index == self.pics.count + 1) {
} else{
pointX = (index + 1) * kWIDTH;
}
self.collectionView.contentOffset = CGPointMake(pointX, 0);
}
#pragma - mark 拖拽开始 关闭定时器
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
[self.timer invalidate];
self.start = !self.start;
}
#pragma - mark 拖拽结束后 重新创建定时器
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
NSInteger sec = self.secNew > 0 ? self.sec : 2 * kSEC;
[self performSelector:@selector(setUpTimer) withObject:nil afterDelay:sec];
}
#pragma - 点击回调
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"%ld",(long)indexPath.item);
if (self.CallBack) {
if (indexPath.item == 0) {
self.CallBack(self.pics.count - 1);
} else if(indexPath.item == self.pics.count + 1){
self.CallBack(0);
}else
{
self.CallBack(indexPath.item - 1);
}
}
}
@end
// 自定义cell JWCollectionViewCell.h
#import <UIKit/UIKit.h>
@interface JWCollectionViewCell : UICollectionViewCell
@property(copy,nonatomic)NSString *url;
@property(copy,nonatomic)NSString *title;
@property(copy,nonatomic)NSString *num;
@end
// 自定义cell JWCollectionViewCell.m
#import "JWCollectionViewCell.h"
#import "UIImageView+WebCache.h"
@interface JWCollectionViewCell ()
@property (weak, nonatomic) IBOutlet UIImageView *imgMain;
@property (weak, nonatomic) IBOutlet UILabel *picNum;
@property (weak, nonatomic) IBOutlet UILabel *lableTitle;
@end
@implementation JWCollectionViewCell
- (void)awakeFromNib {
// Initialization code
}
- (void)setUrl:(NSString *)url
{
_url = url;
[self.imgMain sd_setImageWithURL:[NSURL URLWithString:_url]];
}
- (void)setTitle:(NSString *)title
{
_title = title;
if ([_title isEqualToString:@""]) {
[self.lableTitle removeFromSuperview];
} else {
self.lableTitle.text = _title;
self.lableTitle.textColor = [UIColor redColor];
}
}
- (void)setNum:(NSString *)num
{
_num = num;
self.picNum.text = _num;
self.picNum.textColor = [UIColor redColor];
self.picNum.textAlignment = NSTextAlignmentRight;
}
@end
/ 自定义cell xib拖的 简单做了下约束
// 调用的ViewController
#import "ViewController.h"
#import "JWCarouselFigureView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *picUrls = [NSArray arrayWithObjects:@"http://imgstore.cdn.sogou.com/app/a/100540002/910829.jpg",@"http://bbsimg.tianshi2.net/forum/201410/20/102633tuegrhtk6ldsx6yq.jpg",@"http://cdn.duitang.com/uploads/item/201510/05/20151005204527_VEriN.jpeg",@"http://imgsrc.baidu.com/forum/pic/item/644a1bce36d3d539ca201e213a87e950342ab057.jpg",@"http://img5.duitang.com/uploads/item/201412/27/20141227212121_waEPy.png",
nil];
NSArray *picNames = [NSArray arrayWithObjects:@"椎名真白",@"艾斯德斯",@"友利奈绪",@"十六夜咲夜",@"远坂凛", nil];
JWCarouselFigureView *view = [[JWCarouselFigureView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height * 2 / 5)];
view.pics = picUrls;
view.titles = picNames;
view.CallBack = ^(NSInteger index)
{
NSLog(@"点的是%@",picNames[index]);
};
[self.view addSubview:view];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
代码地址:https://github.com/xueZhiXiaWeiLiang/JWCarouselFigureView
// 其实轮播图的实现也算是很简单的了 今天就带大家做一个简易的轮播图
// 实现功能:带定时器 可以手动拖拽 手动拖拽定时器停止 手动拖拽结束一定时间 定时器重新启动
// 创建一个UIView 子类JWCarouselFigureView
// JWCarouselFigureView.h
#import <UIKit/UIKit.h>
@interface JWCarouselFigureView : UIView
/*图片数组*/
@property(copy,nonatomic)NSArray *pics;
/*标题数组*/
@property(copy,nonatomic)NSArray *titles;
/*轮播时间间隔*/
@property(assign,nonatomic)NSInteger sec;
/*拖拽结束重新开启定时器间隔*/
@property(assign,nonatomic)NSInteger secNew;
/*点击回传*/
@property(copy,nonatomic)void(^CallBack)(NSInteger index);
@end
// JWCarouselFigureView.m具体实现
#import "JWCarouselFigureView.h"
#import "JWCollectionViewCell.h"
#define kWIDTH [UIScreen mainScreen].bounds.size.width
#define kSEC 3
@interface JWCarouselFigureView()<UICollectionViewDataSource,UICollectionViewDelegate>
@property(nonatomic,strong)UICollectionView *collectionView;
@property(assign,nonatomic,getter=isStart)BOOL start;// 判断定时器状态 防止多次创建
@property(weak,nonatomic)NSTimer *timer;
@end
@implementation JWCarouselFigureView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
#pragma - mark collectioView初始化
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
layout.itemSize = CGSizeMake(self.frame.size.width, self.frame.size.height);
layout.minimumInteritemSpacing = 0;
layout.minimumLineSpacing = 0;
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
collectionView.delegate = self;
collectionView.pagingEnabled = YES;
collectionView.dataSource = self;
self.collectionView = collectionView;
[collectionView registerNib:[UINib nibWithNibName:@"JWCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"JWCollectionViewCell"];
// 第一个出现的是第二个item也就是数据的第一条数据
collectionView.contentOffset = CGPointMake(frame.size.width, 0);
[self addSubview:collectionView];
// 初始化定时器
[self setUpTimer];
}
return self;
}
#pragma - collectionView协议方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
JWCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"JWCollectionViewCell" forIndexPath:indexPath];
return [self setDataForCell:cell IndexPath:indexPath];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.pics.count + 2;
}
#pragma - mark cell赋值
- (UICollectionViewCell *)setDataForCell:(JWCollectionViewCell *)cell IndexPath:(NSIndexPath *)indexPath
{
#pragma - mark 判断是第几个cell 第一个cell赋数组最后一个数据,最后一个cell赋值数组第一个数据
NSInteger count = self.pics.count;
if (indexPath.item == 0) {
cell.url = [self.pics lastObject];
cell.title = self.titles.count > 0 ? [self.titles lastObject]:nil;
cell.num = [NSString stringWithFormat:@"%ld/%ld",(unsigned long)self.pics.count,(unsigned long)self.pics.count];
} else if(indexPath.item == count + 1){
cell.url = [self.pics firstObject];
cell.title = self.titles.count > 0 ? [self.titles firstObject]:nil;
cell.num = [NSString stringWithFormat:@"1/%ld",(unsigned long)self.pics.count];
} else
{
cell.url = [self.pics objectAtIndex:indexPath.item - 1];
cell.title = self.titles.count > 0 ? [self.titles objectAtIndex:indexPath.item - 1]:nil;
cell.num = [NSString stringWithFormat:@"%ld/%ld",(long)indexPath.item,(unsigned long)self.pics.count];
}
return cell;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
NSInteger index = scrollView.contentOffset.x / kWIDTH;
#pragma - 手动滑动时候判断滑到第几张 执行相应的跳转
if (index == self.pics.count + 1) {
self.collectionView.contentOffset = CGPointMake(kWIDTH * 1, 0);
} else if(index == 0){
self.collectionView.contentOffset = CGPointMake(kWIDTH * self.pics.count, 0);
}
}
#pragma mark - 定时器创建方法
- (void)setUpTimer
{
if (!_start) {
NSInteger sec = self.sec > 0 ? self.sec : kSEC;
self.timer = [NSTimer timerWithTimeInterval:sec target:self selector:@selector(timerActionMethod) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
_start = !_start;
}
}
// 定时器关联方法
- (void)timerActionMethod
{
NSInteger index = self.collectionView.contentOffset.x / kWIDTH;
NSInteger pointX = 0;
if (index == self.pics.count + 1) {
} else{
pointX = (index + 1) * kWIDTH;
}
self.collectionView.contentOffset = CGPointMake(pointX, 0);
}
#pragma - mark 拖拽开始 关闭定时器
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
[self.timer invalidate];
self.start = !self.start;
}
#pragma - mark 拖拽结束后 重新创建定时器
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
NSInteger sec = self.secNew > 0 ? self.sec : 2 * kSEC;
[self performSelector:@selector(setUpTimer) withObject:nil afterDelay:sec];
}
#pragma - 点击回调
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"%ld",(long)indexPath.item);
if (self.CallBack) {
if (indexPath.item == 0) {
self.CallBack(self.pics.count - 1);
} else if(indexPath.item == self.pics.count + 1){
self.CallBack(0);
}else
{
self.CallBack(indexPath.item - 1);
}
}
}
@end
// 自定义cell JWCollectionViewCell.h
#import <UIKit/UIKit.h>
@interface JWCollectionViewCell : UICollectionViewCell
@property(copy,nonatomic)NSString *url;
@property(copy,nonatomic)NSString *title;
@property(copy,nonatomic)NSString *num;
@end
// 自定义cell JWCollectionViewCell.m
#import "JWCollectionViewCell.h"
#import "UIImageView+WebCache.h"
@interface JWCollectionViewCell ()
@property (weak, nonatomic) IBOutlet UIImageView *imgMain;
@property (weak, nonatomic) IBOutlet UILabel *picNum;
@property (weak, nonatomic) IBOutlet UILabel *lableTitle;
@end
@implementation JWCollectionViewCell
- (void)awakeFromNib {
// Initialization code
}
- (void)setUrl:(NSString *)url
{
_url = url;
[self.imgMain sd_setImageWithURL:[NSURL URLWithString:_url]];
}
- (void)setTitle:(NSString *)title
{
_title = title;
if ([_title isEqualToString:@""]) {
[self.lableTitle removeFromSuperview];
} else {
self.lableTitle.text = _title;
self.lableTitle.textColor = [UIColor redColor];
}
}
- (void)setNum:(NSString *)num
{
_num = num;
self.picNum.text = _num;
self.picNum.textColor = [UIColor redColor];
self.picNum.textAlignment = NSTextAlignmentRight;
}
@end
/ 自定义cell xib拖的 简单做了下约束
// 调用的ViewController
#import "ViewController.h"
#import "JWCarouselFigureView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *picUrls = [NSArray arrayWithObjects:@"http://imgstore.cdn.sogou.com/app/a/100540002/910829.jpg",@"http://bbsimg.tianshi2.net/forum/201410/20/102633tuegrhtk6ldsx6yq.jpg",@"http://cdn.duitang.com/uploads/item/201510/05/20151005204527_VEriN.jpeg",@"http://imgsrc.baidu.com/forum/pic/item/644a1bce36d3d539ca201e213a87e950342ab057.jpg",@"http://img5.duitang.com/uploads/item/201412/27/20141227212121_waEPy.png",
nil];
NSArray *picNames = [NSArray arrayWithObjects:@"椎名真白",@"艾斯德斯",@"友利奈绪",@"十六夜咲夜",@"远坂凛", nil];
JWCarouselFigureView *view = [[JWCarouselFigureView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height * 2 / 5)];
view.pics = picUrls;
view.titles = picNames;
view.CallBack = ^(NSInteger index)
{
NSLog(@"点的是%@",picNames[index]);
};
[self.view addSubview:view];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
代码地址:https://github.com/xueZhiXiaWeiLiang/JWCarouselFigureView
相关文章推荐
- 用代码走进Ftp
- 团队合作
- Func与Action
- java 平台 权限管理
- 多线程
- Ganglia安装
- 调整数组顺序使奇数位于偶数前面,偶数和偶数之间的相对位置不变
- SpringMVC实现注解式权限验证
- 【bzoj4318】OSU! 期望DP
- eclipse关联git的方法 (二)
- Introducing fidlr: FInancial Data LoadeR
- JSR 303 - Bean Validation
- 认识UML中类之间的依赖、关联、聚合、组合、泛化的关系
- SqlServer索引及优化详解
- 个人hbase编程遇到的问题
- 使用泛型元组替代out与ref形式传参
- Android Studio编译保留指定的so库
- ubuntu 64位 出现 error executing aapt 错误
- centos7安装zabbix3.02
- Android loopj 文件上传