自定义轮播图、自定义集合控件的实现
首先声明本篇博客是个人原创,绝非抄袭。
自定义实现轮播图
轮播图一般实现在一款App的首页的最上部分,能够来回滚动的图片,通常这些图片都对应一个网络Url ,用户点击的时候,能够跳转到对应的UIwebView页面。轮播图也可以使用在用户引导页面,只不过这时候轮播图的大小是全屏的,用户可以在轮播图上放一些控件,用来收集用户的信息,当用户进入程序的时候,可以根据这些信息,加载相应的版块内容,或者推荐相应的推送。轮播图也可以在相框的程序中用到,也可以在新闻类App中对应一个专题的整页的滑动,总之轮播图增添了App的用户体验效果,是必不可少的一个技术实现。
本文的轮播图采用工具:
UIScrollView(用于实现轮播效果)、UILabel(用于显示当前是第几张)、NSTimer(用于实现自动轮播)采用封装的思想,降低耦合度,将该功能组件化。
目前实现的功能相对来说比较简单,功能如下:
能够设置轮播图的位置大小、设置录播的一组图片用数组实现、是否自动轮播、自动轮播间隔时间。
使用:
首先引入ScrollerImage.h 和 ScrollerImage.m文件到工程中
调用接口:
-(id)initWithFrame:(CGRect)frame
Arrary:(NSArray *)imageArr
isAutomLunBo:(BOOL)isYes
setLunBoTime:(NSInteger)intervalTime;
例如:
在一个视图控制器中
#import "ScrollerImage.h"//引入自定义轮播图
@property(nonatomic,strong)ScrollerImage * myImageViewScroller;
//轮播图的图片数组
NSArray * arrImg = @[@"1.png",@"2.png",@"3.png",@"4.png",@"5.png",@"6.png",@"7.png",@"8.png",@"9.png"];
self.myImageViewScroller = [[ScrollerImage alloc]initWithFrame:view.frame Arrary:arrImg isAutomLunBo:NO setLunBoTime:2.3];
[view addSubview:self.myImageViewScroller];
代码:
#import <UIKit/UIKit.h> @interface ScrollerImage : UIView<UIScrollViewDelegate> @property(assign)NSInteger count; -(id)initWithFrame:(CGRect)frame Arrary:(NSArray *)imageArr isAutomLunBo:(BOOL)isYes setLunBoTime:(NSInteger)intervalTime; -(void)dealloc; @end
#import "ScrollerImage.h" @interface ScrollerImage () @property (strong, nonatomic) UIScrollView *scroll; @property (strong, nonatomic) UILabel *toKonwCurrentPageLabel; @property(strong,nonatomic)NSTimer * timer; @property(assign)int n; @end @implementation ScrollerImage //自定义轮播图 -(id)initWithFrame:(CGRect)frame Arrary:(NSArray *)imageArr isAutomLunBo:(BOOL)isYes setLunBoTime:(NSInteger)intervalTime;{ if ([super init]) { self.frame = frame; } self.count = imageArr.count; CGFloat kWidth = self.frame.size.width; CGFloat kHeight = self.frame.size.height; //滑块 self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight)]; self.scroll.contentSize = CGSizeMake(kWidth * imageArr.count, kHeight); self.scroll.pagingEnabled = YES; self.scroll.delegate = self; self.scroll.scrollEnabled = YES; [self addSubview:self.scroll]; //显示图片张数 self.toKonwCurrentPageLabel = [[UILabel alloc]initWithFrame:CGRectMake(kWidth - 90, kHeight - 30, 60, 20)]; self.toKonwCurrentPageLabel.layer.masksToBounds = YES; self.toKonwCurrentPageLabel.layer.cornerRadius = 11; self.toKonwCurrentPageLabel.backgroundColor = [UIColor blackColor]; self.toKonwCurrentPageLabel.textColor = [UIColor whiteColor]; self.toKonwCurrentPageLabel.textAlignment = NSTextAlignmentCenter; self.toKonwCurrentPageLabel.font = [UIFont systemFontOfSize:12]; self.toKonwCurrentPageLabel.alpha = 0.3; self.toKonwCurrentPageLabel.text = [NSString stringWithFormat:@"1/共%lu张",self.count]; for (int i = 0; i < imageArr.count; i++) { UIImageView * viewImage = [[UIImageView alloc]initWithFrame:CGRectMake(i*kWidth, 0, kWidth, kHeight)]; viewImage.image = [UIImage imageNamed:imageArr[i]]; [self.scroll addSubview:viewImage]; } [self.scroll addSubview:self.toKonwCurrentPageLabel]; [self.scroll bringSubviewToFront:self.toKonwCurrentPageLabel]; //轮播效果 if (isYes == YES) { self.timer = [NSTimer timerWithTimeInterval:intervalTime target:self selector:@selector(LunBoAction:) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes]; } self.n = 0;//初始化轮播位置 return self; } //LunBo -(void)LunBoAction:(NSTimer *)sender{ self.n +=1; self.scroll.contentOffset = CGPointMake(self.scroll.frame.size.width * (self.n % (int)self.count), 0); int i = self.n %(int)self.count; [self setLabelWith:i contentOffset:self.scroll.frame.size.width andHeight:self.scroll.frame.size.height]; if (self.n == self.count) { self.n = 0; } } //人为滑动图片 -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ CGFloat width = scrollView.frame.size.width; CGFloat height = scrollView.frame.size.height; self.n = scrollView.contentOffset.x/width; [self setLabelWith:self.n contentOffset:width andHeight:height]; } -(void)setLabelWith:(int)i contentOffset:(CGFloat)width andHeight:(CGFloat)height{ self.toKonwCurrentPageLabel.text = [NSString stringWithFormat:@"%d/共%lu张",i+1,self.count]; self.toKonwCurrentPageLabel.frame = CGRectMake(width*(i + 1) - 90, height - 30 , 60, 20); } -(void)dealloc{ self.timer = nil; [self.timer invalidate]; } @end
效果截图:
自定义集合控件的实现
集合视图也能够实现轮播图,我觉得有时间再次研究轮播图的实现,下面使用到集合视图是解决这类问题,看下面的两幅图片,左边的是在请求数据后解析的结果没有录播图,并且上面四个主题“附近的贴”“精编推荐”。。是不固定的主题,有可能某一天主题变化为两个,下面6个主题的板块主题个数也是有可能变化的,主题的多少是根据请求到的数组里的主题个数决定,这里仅仅是模拟功能。右边的图片中,有轮播图,上下两个板块的功能与图片一中的是一样的。
技术点分析:
首先因为主题有可能要变化,根据界面的设计需求,所以最好是使用集合视图UICollectionView 实现。而是否有轮播图可以使用一个布尔值判断,如果有轮播图就开启集合视图的页眉,如果没有就关闭集合视图的页眉,并动态的改变位置。比较难以实现的是,如何在一个 UIViewController 中实现有两个 UICollectionView
,对于这个问题,可以在 UICollectionViewDelegate 的协议方法中,根据可重用ID做一下判断即可。
实现功能的全部源代码:
需要源代码的园友可以在左侧QQ我哦,如有转载请说明出处,谢谢。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
#import "ViewController.h" #import "Cell.h" #import "HeaderView.h" #import "FooterView.h" #import "ScrollerImage.h"//引入自定义轮播图 @interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout> { BOOL isHaveLunBo;//判断是否有轮播图 } @property(nonatomic,strong)UIScrollView * scroll; @property(nonatomic,strong)ScrollerImage * myImageViewScroller; @property(nonatomic,strong)UICollectionView * collectionView1; @property(nonatomic,strong)UICollectionView * collectionView2; //测试数据 @property(nonatomic,strong)NSMutableArray * arrayOfTestDataSouce1; @property(nonatomic,strong)NSMutableArray * arrayOfTestDataSouce2; @end @implementation ViewController //-lazy -(NSMutableArray *)arrayOfTestDataSouce1{ if (_arrayOfTestDataSouce1 == nil) { //我在这里给数据添加数据,可以在请求到数据后再添加数据 NSArray * testArr = @[@"A",@"B",@"C",@"D"]; self.arrayOfTestDataSouce1 = [NSMutableArray arrayWithArray:testArr]; NSLog(@"%@",self.arrayOfTestDataSouce1); } return _arrayOfTestDataSouce1; } -(NSMutableArray *)arrayOfTestDataSouce2{ if (_arrayOfTestDataSouce2 == nil) { //我在这里给数据添加数据,可以在请求到数据后再添加数据 NSArray * testArr = @[@"AA",@"BB",@"CC",@"DD",@"EE",@"FF"]; self.arrayOfTestDataSouce2 = [NSMutableArray arrayWithArray:testArr]; NSLog(@"%@",self.arrayOfTestDataSouce2); } return _arrayOfTestDataSouce2; } - (void)viewDidLoad { [super viewDidLoad]; //关闭毛玻璃效果 self.navigationController.navigationBar.translucent = NO; //添加 集合视图1 UIView * vi = [[UIView alloc] init]; vi.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 125); vi.backgroundColor = [UIColor redColor]; UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; //配置属性 //1.设置每个item的大小 layout.itemSize = CGSizeMake(self.view.bounds.size.width / 2 - 10, 50); //2.设置缩进量 (上,左,下,右) layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5); //3.设置行的最小间距 layout.minimumLineSpacing = 2.5; //4.设置item的最小间距 layout.minimumInteritemSpacing = 10; self.collectionView1 = [[UICollectionView alloc] initWithFrame:vi.frame collectionViewLayout:layout]; //这里巨坑啊,设定代理一定要写到初始化集合视图的下面 self.collectionView1.delegate = self; self.collectionView1.dataSource = self; self.collectionView1.backgroundColor = [UIColor brownColor]; [vi addSubview:self.collectionView1]; [self.view addSubview:vi]; //判断是否有轮播图(默认有-YES) isHaveLunBo = YES; //添加 集合视图2 UICollectionViewFlowLayout *layout2 = [[UICollectionViewFlowLayout alloc] init]; //配置属性 //1.设置每个item的大小 layout2.itemSize = CGSizeMake(50, 50); //2.设置缩进量 (上,左,下,右) layout2.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5); //3.设置行的最小间距 layout2.minimumLineSpacing = 10; //4.设置item的最小间距 layout2.minimumInteritemSpacing = 10; //设置大小 if (isHaveLunBo) { self.collectionView2 = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 125, self.collectionView1.frame.size.width, 180 + 125) collectionViewLayout:layout2]; }else{ self.collectionView2 = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 125, self.collectionView1.frame.size.width, 180) collectionViewLayout:layout2]; } self.collectionView2.delegate = self; self.collectionView2.dataSource = self; [self.view addSubview:self.collectionView2]; //注册cell [self.collectionView1 registerClass:[Cell class] forCellWithReuseIdentifier:@"item1"]; [self.collectionView2 registerClass:[Cell class] forCellWithReuseIdentifier:@"item2"]; //注册页眉 [self.collectionView1 registerClass:[HeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"]; [self.collectionView2 registerClass:[FooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"]; //注册页脚 [self.collectionView2 registerClass:[HeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"]; [self.collectionView2 registerClass:[FooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"]; } #pragma mark - UICollectionViewDataSource - //设置分区的item数目 - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { if (collectionView == self.collectionView1) { return self.arrayOfTestDataSouce1.count; } else { return self.arrayOfTestDataSouce2.count; } } //设置分区数目 - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { if (collectionView == self.collectionView1) { return 1; } else { return 1; } } #pragma Mark======设置自定义的cell - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ if (collectionView == self.collectionView1) { Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"item1" forIndexPath:indexPath]; cell.lab.text = self.arrayOfTestDataSouce1[indexPath.item]; cell.lab.frame = cell.bounds; return cell; } else { Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"item2" forIndexPath:indexPath]; cell.lab.text = self.arrayOfTestDataSouce2[indexPath.item]; return cell; } } #pragma Mark======设置页眉与页脚的视图 -(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{ if ([kind isEqualToString:UICollectionElementKindSectionHeader]) { if (collectionView == self.collectionView2) { //返回页眉 HeaderView * view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath]; //view.titleLabel.text = @"页眉,可以在黄色区域放轮播图"; if (isHaveLunBo == YES) { //轮播图的图片数组 NSArray * arrImg = @[@"1.png",@"2.png",@"3.png",@"4.png",@"5.png",@"6.png",@"7.png",@"8.png",@"9.png"]; self.myImageViewScroller = [[ScrollerImage alloc]initWithFrame:view.frame Arrary:arrImg isAutomLunBo:NO setLunBoTime:2.3]; [view addSubview:self.myImageViewScroller]; return view; }else{ return nil; } }else{ return nil; } } else { //返回页脚 // FooterView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath]; // footer.footerLabel.text = @"页脚"; // return footer; return nil; } } #pragma mark - UICollectionViewDelegateFlowLayout - //动态配置每个分区的item的size大小 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.section == 0) { return CGSizeMake((self.view.frame.size.width - 15)/2, 50); } return CGSizeMake((self.view.frame.size.width - 60)/3, 50); } //动态配置item的缩进量 - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section { if (section == 0) { //上、左、下、右 return UIEdgeInsetsMake(10, 5, 10, 5); } return UIEdgeInsetsMake(10, 5, 10, 5); } //动态配置item 左右最小间距 - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section { return 5; } //动态配置行的最小间距 - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section { return 5; } //动态的设置页眉 -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{ if (collectionView == self.collectionView1) { //这里也可以仿照下面写法,为 collectionView1 设定是否添加页眉 return CGSizeMake(0, 0); }else{ if (isHaveLunBo) { return CGSizeMake(20, 100); }else{ return CGSizeMake(0, 0); } } } //动态的设置页脚 -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{ return CGSizeMake(0, 0); } #pragma mark - UICollectionViewDelegate - - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { //选中某一行的点击事件写这里 NSLog(@"选择了"); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
#import <UIKit/UIKit.h> @interface ScrollerImage : UIView<UIScrollViewDelegate> @property(assign)NSInteger count; -(id)initWithFrame:(CGRect)frame Arrary:(NSArray *)imageArr isAutomLunBo:(BOOL)isYes setLunBoTime:(NSInteger)intervalTime; -(void)dealloc; @end
#import "ScrollerImage.h" @interface ScrollerImage () @property (strong, nonatomic) UIScrollView *scroll; @property (strong, nonatomic) UILabel *toKonwCurrentPageLabel; @property(strong,nonatomic)NSTimer * timer; @property(assign)int n; @end @implementation ScrollerImage //自定义轮播图 -(id)initWithFrame:(CGRect)frame Arrary:(NSArray *)imageArr isAutomLunBo:(BOOL)isYes setLunBoTime:(NSInteger)intervalTime;{ if ([super init]) { self.frame = frame; } self.count = imageArr.count; CGFloat kWidth = self.frame.size.width; CGFloat kHeight = self.frame.size.height; //滑块 self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight)]; self.scroll.contentSize = CGSizeMake(kWidth * imageArr.count, kHeight); self.scroll.pagingEnabled = YES; self.scroll.delegate = self; self.scroll.scrollEnabled = YES; [self addSubview:self.scroll]; //显示图片张数 self.toKonwCurrentPageLabel = [[UILabel alloc]initWithFrame:CGRectMake(kWidth - 90, kHeight - 30, 60, 20)]; self.toKonwCurrentPageLabel.layer.masksToBounds = YES; self.toKonwCurrentPageLabel.layer.cornerRadius = 11; self.toKonwCurrentPageLabel.backgroundColor = [UIColor blackColor]; self.toKonwCurrentPageLabel.textColor = [UIColor whiteColor]; self.toKonwCurrentPageLabel.textAlignment = NSTextAlignmentCenter; self.toKonwCurrentPageLabel.font = [UIFont systemFontOfSize:12]; self.toKonwCurrentPageLabel.alpha = 0.3; self.toKonwCurrentPageLabel.text = [NSString stringWithFormat:@"1/共%lu张",self.count]; for (int i = 0; i < imageArr.count; i++) { UIImageView * viewImage = [[UIImageView alloc]initWithFrame:CGRectMake(i*kWidth, 0, kWidth, kHeight)]; viewImage.image = [UIImage imageNamed:imageArr[i]]; [self.scroll addSubview:viewImage]; } [self.scroll addSubview:self.toKonwCurrentPageLabel]; [self.scroll bringSubviewToFront:self.toKonwCurrentPageLabel]; //轮播效果 if (isYes == YES) { self.timer = [NSTimer timerWithTimeInterval:intervalTime target:self selector:@selector(LunBoAction:) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes]; } self.n = 0;//初始化轮播位置 return self; } //LunBo -(void)LunBoAction:(NSTimer *)sender{ self.n +=1; self.scroll.contentOffset = CGPointMake(self.scroll.frame.size.width * (self.n % (int)self.count), 0); int i = self.n %(int)self.count; [self setLabelWith:i contentOffset:self.scroll.frame.size.width andHeight:self.scroll.frame.size.height]; if (self.n == self.count) { self.n = 0; } } //人为滑动图片 -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ CGFloat width = scrollView.frame.size.width; CGFloat height = scrollView.frame.size.height; self.n = scrollView.contentOffset.x/width; [self setLabelWith:self.n contentOffset:width andHeight:height]; } -(void)setLabelWith:(int)i contentOffset:(CGFloat)width andHeight:(CGFloat)height{ self.toKonwCurrentPageLabel.text = [NSString stringWithFormat:@"%d/共%lu张",i+1,self.count]; self.toKonwCurrentPageLabel.frame = CGRectMake(width*(i + 1) - 90, height - 30 , 60, 20); } -(void)dealloc{ self.timer = nil; [self.timer invalidate]; } @end
#import <UIKit/UIKit.h> @interface FooterView : UICollectionReusableView @property (nonatomic, retain) UILabel *footerLabel; @end
#import "FooterView.h" @implementation FooterView - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self addSubview:self.footerLabel]; } return self; } - (UILabel *)footerLabel { if (!_footerLabel) { self.footerLabel = [[UILabel alloc] initWithFrame:self.bounds]; _footerLabel.backgroundColor = [UIColor greenColor]; } return _footerLabel; } @end
#import <UIKit/UIKit.h> @interface HeaderView : UICollectionReusableView @property (nonatomic, retain) UILabel *titleLabel; @end
#import "HeaderView.h" @implementation HeaderView - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self addSubview:self.titleLabel]; } return self; } - (UILabel *)titleLabel { if (!_titleLabel) { self.titleLabel = [[UILabel alloc] initWithFrame:self.bounds]; _titleLabel.backgroundColor = [UIColor yellowColor]; } return _titleLabel; } @end
#import <UIKit/UIKit.h> @interface Cell : UICollectionViewCell @property(nonatomic,strong)UILabel * lab; @end
#import "Cell.h" @implementation Cell - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { //按照此格式,添加一些其他控件 [self.contentView addSubview:self.lab]; } return self; } - (UILabel *)lab { if (!_lab) { self.lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; //测试颜色 _lab.backgroundColor = [UIColor greenColor]; _lab.textAlignment = NSTextAlignmentCenter; _lab.font = [UIFont systemFontOfSize:15]; } return _lab; } @end
源代码实现效果:
左边图片假设没有请求到轮播图,右边图片假设请求到轮播图,关键代码
isHaveLunBo = YES;如果为NO,不显示录播图,具体情况根据网络请求结果处理,这里仅仅模拟效果。
单单就轮播图实现了优化: