// 項目中輪播圖的登場率還是很大的,之前有用到輪播三方 但看他源碼的時候發現 創建了好多組數據 這無形中浪費了一部分內存
// 其實輪播圖的實現也算是很簡單的了 今天就帶大家做一個簡易的輪播圖
// 實現功能:帶定時器 可以手動拖拽 手動拖拽定時器停止 手動拖拽結束一定時間 定時器重新啓動
// 創建一個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