此篇介紹另一種圖片輪播器的優化,採用UICollectionView來實現,因爲系統已經爲UICollectionView做好了優化
#import <UIKit/UIKit.h>
@protocol CarouselDelegate <NSObject>
//點擊事件
-(void)clickedAtIndex:(NSInteger)index;
@end
@interface CarouselView : UIView
//代理
@property(assign,nonatomic) id<CarouselDelegate> delegate;
//數據源
@property (strong,nonatomic) NSMutableArray *dataSources;
//開啓自動滾動
-(void)startAutoScroll;
@end
#import "CarouselView.h"
#import "CarouselCell.h"
// 每一組最大的行數
#define TotalRowsInSection (2000 * self.dataSources.count)
#define DefaultRow (NSUInteger)(TotalRowsInSection * 0.5)
@interface CarouselView()<UICollectionViewDataSource,UICollectionViewDelegate>
//容器
@property (strong, nonatomic) UICollectionView *collectionView;
//分頁控制器
@property (strong, nonatomic) UIPageControl *pageControl;
//定時器
@property (nonatomic , strong) NSTimer *timer;
//自動滾動,默認不開啓
@property (assign,nonatomic) BOOL autoScroll;
@end
@implementation CarouselView
-(instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
self.frame = frame;
[self initSubviews:frame];
}
return self;
}
-(void)initSubviews:(CGRect)frame
{
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.itemSize = frame.size;
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
flowLayout.minimumLineSpacing = 0;
self.collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
self.collectionView.showsHorizontalScrollIndicator = NO;
self.collectionView.pagingEnabled = YES;
self.collectionView.backgroundColor = [UIColor lightGrayColor];
[self addSubview:self.collectionView];
[self.collectionView registerClass:[CarouselCell class] forCellWithReuseIdentifier:@"carouselCell"];
self.pageControl = [[UIPageControl alloc] init];
self.pageControl.center = CGPointMake(frame.size.width * 0.5, frame.size.height - 30);
self.pageControl.bounds = CGRectMake(0, 0, 150, 40);
self.pageControl.pageIndicatorTintColor = [UIColor grayColor];
self.pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
self.pageControl.enabled = NO;
self.pageControl.numberOfPages = self.dataSources.count;
[self addSubview:self.pageControl];
if (self.autoScroll) {
[self addTimer];
}
}
-(void)setDataSources:(NSMutableArray *)dataSources
{
_dataSources = dataSources;
//設置分頁控制器頁數
self.pageControl.numberOfPages = self.dataSources.count;
//刷新數據
[self.collectionView reloadData];
//設置默認組
[self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:DefaultRow inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}
-(void)startAutoScroll
{
self.autoScroll = YES;
[self addTimer];
}
/**
* 移除定時器
*/
- (void)removeTimer
{
[self.timer invalidate];
self.timer = nil;
}
/**
* 添加定時器
*/
- (void)addTimer
{
self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(next) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
/**
* 下一頁
*/
- (void)next
{
NSIndexPath *visiablePath = [[self.collectionView indexPathsForVisibleItems] firstObject];
NSUInteger visiableItem = visiablePath.item;
if ((visiablePath.item % self.dataSources.count) == 0) { // 第0張圖片
[self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:DefaultRow inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
visiableItem = DefaultRow ;
}
NSUInteger nextItem = visiableItem + 1;
[self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:nextItem inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return TotalRowsInSection;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"carouselCell";
CarouselCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
if (!cell) {
cell = [[NSBundle mainBundle] loadNibNamed:@"CarouselCell" owner:self options:nil][0];
}
cell.dataModel = self.dataSources[indexPath.item % self.dataSources.count];
return cell;
}
#pragma mark - UICollectionViewDelegate
/**
* cell顯示結束之後調用(滑動了一頁)
*/
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *visiablePath = [[collectionView indexPathsForVisibleItems] firstObject];
//設置pageControl的當前頁
self.pageControl.currentPage = visiablePath.item % self.dataSources.count;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger index = indexPath.item % self.dataSources.count;
if ([self.delegate respondsToSelector:@selector(clickedAtIndex:)]) {
[self.delegate clickedAtIndex:index];
}
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
if (self.autoScroll) {
[self removeTimer];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
if (self.autoScroll) {
[self addTimer];
}
}
@end
#import <UIKit/UIKit.h>
#import "CarouselModel.h"
@interface CarouselCell : UICollectionViewCell
//數據模型
@property (strong,nonatomic) CarouselModel *dataModel;
@end
#import "CarouselCell.h"
#import "UIImageView+WebCache.h"
@interface CarouselCell()
//顯示的圖片
@property (weak,nonatomic) IBOutlet UIImageView *imageView;
//標題
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@end
@implementation CarouselCell
-(instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self = [[NSBundle mainBundle]loadNibNamed:@"CarouselCell" owner:self options:nil].lastObject;
}
return self;
}
//重寫屬性,設置值
-(void)setDataModel:(CarouselModel *)dataModel
{
_dataModel = dataModel;
[self.imageView sd_setImageWithURL:[[NSURL alloc] initWithString:_dataModel.imageUrl] placeholderImage:[UIImage imageNamed:@"1"]];
self.titleLabel.text = _dataModel.labelText;
}
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
@end
VC中使用
self.automaticallyAdjustsScrollViewInsets = NO;
NSMutableArray *dataList = [[NSMutableArray alloc]init];
NSMutableArray *dataArr = [[NSMutableArray alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"carouselArr.plist" ofType:nil]];
for (NSDictionary *dic in dataArr) {
CarouselModel *model = [[CarouselModel alloc]init];
model.imageUrl = [dic objectForKey:@"imageUrl"];
model.contentUrl = [dic objectForKey:@"contentUrl"];
model.labelText = [dic objectForKey:@"textLable"];
[dataList addObject:model];
}
CarouselView *view1 = [[CarouselView alloc]initWithFrame:CGRectMake(20, 100, self.view.frame.size.width - 40, (self.view.frame.size.width - 40) * 0.5)];
view1.delegate = self;
[view1 startAutoScroll];
view1.dataSources = dataList;
[self.view addSubview:view1];