无限轮播图的简单封装

先让大家来看下Demo:

无限轮播图的简单封装_第1张图片
无限轮播.gif

1.这只是一个简单的小案例,在这我学要学的就是如何去封装一个,图片轮播器.之后我们在使用的时候,只需要2行代码就可以轻松完成.

a.首先你需要准备完成Demo所需要的数据,以下是加载数据源的方法:

  - (void) loadData {
  NSMutableArray *Marr = [[NSMutableArray alloc] init];
for (int i = 0 ; i < 3; i++) {
    NSString *imageName = [NSString stringWithFormat:@"%02zd.jpg",(i+1)];
    NSURL *url = [[NSBundle mainBundle] URLForResource:imageName withExtension:nil];
    [Marr addObject:url];
}  
_urls = Marr.copy;
}

b.数据加载完成之后,你需要做的就是考虑如何去搭建UI界面.界面如果需要滑动,你首先想到的是ScrollView以及继承自scrollView的其他控件.在这,我们就直接使用UICollectionView.

首先我们创建一个类继承自UICollectionView

@interface TBLLoopView : UICollectionView

在这个类里面,我们需要做的就只有三件事:
1.提供一个接口,供外界使用.
- (instancetype) initWithImageUrls:(NSArray *)urls didSelectedIndex:(void(^)(NSInteger))selectedIndex;
2.完成数据源,代理方法.

self.delegate = self;
self.dataSource = self;

3.实现无限轮播(基本思路就是,设置数据源为多组,每当滚到第一张就将偏移值悄悄设置为count-1)

NSInteger offset = scrollView.contentOffset.x / scrollView.bounds.size.width; 
//实现无线轮播
if (offset == 0 || offset == ([self numberOfItemsInSection:0]) - 1) {    
    //切换图片
    offset = _urls.count - (offset == 0 ? 0 : 1); 
    scrollView.contentOffset = CGPointMake(offset * scrollView.bounds.size.width, 0);
}

C.collectionView需要设置Layout属性,再次我们自定义一个FlowLayout让它继承自UICollectionViewFlowLayout,重写prepareLayout方法.完成我们需要设置的属性

- (void)prepareLayout {

[super prepareLayout];

//设置属性
self.itemSize = self.collectionView.bounds.size;
self.minimumLineSpacing = 0;
self.minimumInteritemSpacing = 0;
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;

self.collectionView.pagingEnabled = YES;
self.collectionView.bounces = NO;
self.collectionView.showsVerticalScrollIndicator = NO;
self.collectionView.showsHorizontalScrollIndicator = NO;

}

D.最后需要自定义Cell完成Cell的赋值.以及初始化Cell的时候创建UIImageView.

- (instancetype) initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
    _imageView = [[UIImageView alloc] initWithFrame:self.contentView.bounds];
    [self.contentView addSubview:_imageView];
    }
return self;
}
- (void)setUrl:(NSURL *)url{
_url = url;    
NSData *data = [NSData dataWithContentsOfURL:url];
_imageView.image = [UIImage imageWithData:data];
}

这样一个简单的图片轮播器就封装完成了.在这个Demo里面重点是怎么实现图片轮播的思路.大致思路如下图:

无限轮播图的简单封装_第2张图片
1F431B9D-30BC-48E1-8D11-6F6340033148.png

你可能感兴趣的:(无限轮播图的简单封装)