本文共 32166 字,大约阅读时间需要 107 分钟。
参考框架:LazyScrollView:
==========1.scrollView 实现图片轮播
#import "ViewController.h"
#define kScrollViewSize (_scrollView.frame.size)
#define kImageCount 5
@interface ViewController ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutletUIScrollView *scrollView;
@property (weak, nonatomic) IBOutletUIPageControl *pageControl;
@property (nonatomic,strong)NSTimer *timer;
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
[self setupUI];
}
#pragma mark -
#pragma mark - 设置UI界面
- (void)setupUI {
// 设置控制器成为scrollView的代理
_scrollView.delegate =self;
[selfsetupScrollView];
[selfsetupPageControll];
// 创建计时器
[selfinitImageTimer];
}
#pragma mark -
#pragma mark - 创建计时器
- (void)initImageTimer {
/**
scheduled 计划,安排
interval : 间隔
target : 一般指控制器
selector: 方法
userInfo : 用户自定义的参数
repeats: 重复
每隔1秒钟调用控制器的 didClickButton:方法,传递的参数为nil
一旦创建就会立即生效
在使用timer的时候,如果调用了 invalidate方法,那么这个计时器就不会再次生效
重新创建新的timer
*/
_timer = [NSTimerscheduledTimerWithTimeInterval:1
target:self
selector:@selector(didClickButton:)
userInfo:nil
repeats:YES];
// [_timer fire]; 调用fire ,这个计时器会立即执行,不会等待 interval设置的时间
//把图片轮播的NStime的优先级提高
NSRunLoop *mainLoop = [NSRunLoopmainRunLoop];
[mainLoop addTimer:_timerforMode:NSRunLoopCommonModes];
}
/**
在开始拖拽的时候,把计时器停止
invalidate 无效的意思
*/
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
// 让计时器无效
[_timer invalidate];
_timer=nil;
}
/**
当停止拖拽的时候,让计时器开始工作
手指离开scrollView的时候
*/
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
// [_timer fire];
[self initImageTimer];
}
#pragma mark -
#pragma mark - scrollView设置
- (void)setupScrollView {
// 取出scrollView的size
// CGSize scrollViewSize = _scrollView.frame.size;
for (int i =0; i <kImageCount; i++) {
// 计算imageView的x值
CGFloat imageViewX = i * kScrollViewSize.width;
UIImageView *imageView = [[UIImageViewalloc]initWithFrame:CGRectMake(imageViewX,0,kScrollViewSize.width,kScrollViewSize.height)];
// 设置图片
// imageView.image =[UIImage imageNamed:@"img_01"];
// 拼接图片的名称
NSString *imageName = [NSStringstringWithFormat:@"img_%02d",i +1];
imageView.image = [UIImageimageNamed:imageName];
// 添加到scrollView
[_scrollView addSubview:imageView];
}
// 设置 scrollView的contentSize
_scrollView.contentSize =CGSizeMake(kImageCount *kScrollViewSize.width,0);
// 隐藏滚动指示器
_scrollView.showsHorizontalScrollIndicator =NO;
// scrollView的分页效果 (根据scrollView的宽度进行分页的)
_scrollView.pagingEnabled =YES;
}
#pragma mark -
#pragma mark - 设置pageControll
- (void)setupPageControll {
// 设置总共有几个点
_pageControl.numberOfPages =kImageCount;
// 设置指示器的颜色
// 非当前的指示器
_pageControl.pageIndicatorTintColor = [UIColorgrayColor];
// 设置当前指示器的颜色
_pageControl.currentPageIndicatorTintColor = [UIColorredColor];
// 设置当前在第几个点 , 取值范围是 0 .. numberOfPages - 1
// 设置的currentPage如果超出最大的范围,就在最后一个显示
// 设置的currentPage如果超出最小的范围就在第一个显示
_pageControl.currentPage =0;
//注意:pagecontrol 要放在scrowView后面设置,否则pagecontrol可能不显示;
#pragma mark -
#pragma mark - 当scrollView停止减速的时候调用
// Decelerating 减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
// currentPage = scrollView.contentOffset.x / kScrollViewSize.width
_pageControl.currentPage = scrollView.contentOffset.x / kScrollViewSize.width;
}
- (IBAction)didClickButton:(id)sender {
/**
1. 取出scrollView的contentOffset
2. 取出 pagecontroll的 currentPage
3. 进行修改
4. 赋值回去
*/
// 1. 取出 contentOffset
CGPoint offset =_scrollView.contentOffset;
// 2. currentPage
NSInteger currentPage = _pageControl.currentPage;
// 3. 进行修改
if (currentPage == 4) {
// 到了最后一张,再次点击的时候,到第一张图片的位置
// currentPage 修改为0
currentPage = 0;
// 修改 scrollView的contentOffset
offset = CGPointZero;
} else {
currentPage += 1;
offset.x += kScrollViewSize.width;
}
// 4. 赋值回去
_pageControl.currentPage = currentPage;
[_scrollViewsetContentOffset:offsetanimated:YES];
}
@end
======================scrollview实现轮播2,直接设置image数组就能用,分模型的数组,或者urlStr数组,nameStr数组
#import <UIKit/UIKit.h>
@class LYHomeinnerAdvertiseView;
@protocol LYHomeinnerAdvertiseViewdelegate <NSObject>
-(void)LYHomeinnerAdvertiseView:(LYHomeinnerAdvertiseView *)LYHomeinnerAdvertiseView mark:(NSString *)markstr url:(NSString *)url;
@end
@interface LYHomeinnerAdvertiseView : UIView
@property(nonatomic,strong)NSArray *bannerArr;
@property(nonatomic,copy)NSString *homebanner;
@property(nonatomic,assign)id<LYHomeinnerAdvertiseViewdelegate>delegate;
@end
**************
#import "LYHomeinnerAdvertiseView.h"
#import "LYHomelunbobannerModel.h"
#import "Header.h"
@interface LYHomeinnerAdvertiseView()<UIScrollViewDelegate>
@property(nonatomic,strong)UIScrollView *headerScroll;
@property(nonatomic,strong)UIPageControl *pageCtrl;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)NSArray *imgeArr;
@property(nonatomic,strong)UIImageView *adoneView;
@property(nonatomic,strong)UIImageView *adtwoView;
@property(nonatomic,strong)UIImageView *adthreeView;
@property(nonatomic,strong)UIImageView *adfourView;
@property(nonatomic,strong)UIImageView *adfiveView;
@property(nonatomic,strong)UIImageView *adsixView;
@end
@implementation LYHomeinnerAdvertiseView
-(NSArray *)imgeArr{
if(nil==_imgeArr){ //,@"adtwo",bannerhomeOne,tabheadscrolImage
_imgeArr = [[NSArray alloc]init];
}
return _imgeArr;
}
-(instancetype)initWithFrame:(CGRect)frame{
if(self=[super initWithFrame:frame]){
NSLog(@"view执行");
self.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"bannerhomeOne"]];
}
return self;
}
-(void)initView{
[self setHeadView];//
if ([self.timer isValid]) {
[self.timer invalidate];
self.timer = nil;
}
if(self.headerScroll){
if(!self.timer && !self.timer.isValid){
[self NSTimers];
}
}
}
-(void)NSTimers{
NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(lunbo) userInfo:nil repeats:YES];
self.timer=timer;
[[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
}
//轮播headerview
-(void)setHeadView{
if(!self.headerScroll){
self.headerScroll=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, ADHEIGHT)];
[self addSubview: self.headerScroll];
}
self.headerScroll.tag=14004;
self.headerScroll.delegate=self;
for (UIView *v in self.headerScroll.subviews) {
[v removeFromSuperview];
}
for(int i=0;i<self.imgeArr.count;i++){
LYHomelunbobannerModel *bannemodel=self.imgeArr[i];
UIImageView *imageV=[[UIImageView alloc]initWithFrame:CGRectMake(i*WIDTH, 0, WIDTH, ADHEIGHT)];
imageV.userInteractionEnabled=YES;
imageV.tag=14100+i;
[ self.headerScroll addSubview:imageV];
NSURL *url=[NSURL URLWithString:bannemodel.ad_code];
NSData *data=[NSData dataWithContentsOfURL:url];
UIImage *image=[UIImage imageWithData:data];
imageV.image=image;
imageV.backgroundColor=[UIColor whiteColor];
if(i==0){
self.adoneView=imageV;
}else if(i==1){
self.adtwoView=imageV;
}else if(i==2){
self.adthreeView=imageV;
}else if(i==3){
self.adfourView=imageV;
}else if(i==4){
self.adfiveView=imageV;
}else if(i==5){
self.adsixView=imageV;
}
UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(taps:)];
[imageV addGestureRecognizer:tap];
}
self.headerScroll.contentSize=CGSizeMake(WIDTH*self.imgeArr.count+1, 0);
self.headerScroll.pagingEnabled=YES;
self.headerScroll.showsHorizontalScrollIndicator=NO;
UIPageControl *pageCtr=[[UIPageControl alloc]init];
self.pageCtrl=pageCtr;
pageCtr.numberOfPages=self.imgeArr.count;
pageCtr.currentPage=0;
pageCtr.bounds=CGRectMake(0, 0, 100, 20);
pageCtr.center=CGPointMake(self.center.x,100);
pageCtr.pageIndicatorTintColor=[UIColor grayColor];
pageCtr.currentPageIndicatorTintColor=[UIColor whiteColor];
[self addSubview:pageCtr];
}
-(void)taps:(UITapGestureRecognizer *)tap {
if(tap.view==self.adoneView){
//取现LYHomelunbobannerModel *bannermodel=self.imgeArr[0];
if([self.delegate respondsToSelector:@selector(LYHomeinnerAdvertiseView:mark:url:)]){
[self.delegate LYHomeinnerAdvertiseView:self mark:@"adoneView" url:bannermodel.ad_link];
}
}else if(tap.view==self.adtwoView){
//LYHomelunbobannerModel *bannermodel=self.imgeArr[1];
if([self.delegate respondsToSelector:@selector(LYHomeinnerAdvertiseView:mark:url:)]){
[self.delegate LYHomeinnerAdvertiseView:self mark:@"adtwoView" url:bannermodel.ad_link];
}
}else if(tap.view==self.adthreeView){
//LYHomelunbobannerModel *bannermodel=self.imgeArr[2];
if([self.delegate respondsToSelector:@selector(LYHomeinnerAdvertiseView:mark:url:)]){
[self.delegate LYHomeinnerAdvertiseView:self mark:@"adthreeView" url:bannermodel.ad_link];
}
}else if(tap.view==self.adfourView){
//LYHomelunbobannerModel *bannermodel=self.imgeArr[3];
if([self.delegate respondsToSelector:@selector(LYHomeinnerAdvertiseView:mark:url:)]){
[self.delegate LYHomeinnerAdvertiseView:self mark:@"adthreeView" url:bannermodel.ad_link];
}
}else if(tap.view==self.adfiveView){
//LYHomelunbobannerModel *bannermodel=self.imgeArr[4];
if([self.delegate respondsToSelector:@selector(LYHomeinnerAdvertiseView:mark:url:)]){
[self.delegate LYHomeinnerAdvertiseView:self mark:@"adthreeView" url:bannermodel.ad_link];
}
}else if(tap.view==self.adsixView){
//LYHomelunbobannerModel *bannermodel=self.imgeArr[5];
if([self.delegate respondsToSelector:@selector(LYHomeinnerAdvertiseView:mark:url:)]){
[self.delegate LYHomeinnerAdvertiseView:self mark:@"adthreeView" url:bannermodel.ad_link];
}
}
}
-(void)lunbo{
// 1. 取出 contentOffset
CGPoint offset =self.headerScroll.contentOffset;
if(offset.x>self.imgeArr.count*WIDTH){
offset=CGPointMake(self.imgeArr.count*WIDTH, 0);
}
// 2. currentPage
NSInteger currentPage = self.pageCtrl.currentPage;
NSLog(@"偏移量0ffset---%.f----currentPage---%tu",offset.x,currentPage);
// 3. 进行修改
if (currentPage ==self.imgeArr.count-1) {
// 到了最后一张,再次点击的时候,到第一张图片的位置
// currentPage 修改为0
currentPage = 0;
// 修改 scrollView的contentOffset
offset = CGPointZero;
} else {
currentPage += 1;
offset.x += WIDTH;
}
NSLog(@"0ffset--02-%f----currentPage---%tu",offset.x,currentPage);
// 4. 赋值回去
self.pageCtrl.currentPage = currentPage;
[self.headerScroll setContentOffset:offset animated:YES];
}
/**
在开始拖拽的时候,把计时器停止
invalidate 无效的意思
*/
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
// 让计时器无效
if ([self.timer isValid]) {
[self.timer invalidate];
self.timer = nil;
NSLog(@"定时器无效1");
}
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
NSLog(@"停止拖拽");
}
/**
当停止加速的时候,让计时器开始工作
手指离开scrollView的时候
*/
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
NSLog(@"停止减速");
if(!self.timer && !self.timer.isValid){
[self NSTimers];
}
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
NSLog(@"正在滚动");
NSInteger pageIndex=self.headerScroll.contentOffset.x/self.headerScroll.frame.size.width;
self.pageCtrl.currentPage=pageIndex;
}
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
NSLog(@"结束滚动");
}
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
UIView *view = [super hitTest:point withEvent:event];
//优先判断子视图可否响应事件
UIView *tempView;
tempView = [self getTargetView:self point:point event:event];
view = tempView;
return view;
}
- (UIView *)getTargetView:(UIView *)view
point:(CGPoint)point
event:(UIEvent *)event
{
__block UIView *subView;
//逆序 由层级最低 也就是最上层的子视图开始
[view.subviews enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//point 从view 转到 obj中
CGPoint hitPoint = [obj convertPoint:point fromView:view];
// NSLog(@"%@ - %@",NSStringFromCGPoint(point),NSStringFromCGPoint(hitPoint));
if([obj pointInside:hitPoint withEvent:event])//在当前视图范围内
{
if(obj.subviews.count != 0)
{
//如果有子视图 递归
subView = [self getTargetView:obj point:hitPoint event:event];
if(!subView)
{ //如果没找到 提交当前视图
subView = obj;
}
}
else
{
subView = obj;
}
*stop = YES;
}
else//不在当前视图范围内
{
if(obj.subviews.count != 0)
{
//如果有子视图 递归
subView = [self getTargetView:obj point:hitPoint event:event];
}
}
}];
return subView;
}
//请求接口数据后,吧数据传过来后,根据图片的数量创建轮播图
-(void)setBannerArr:(NSArray *)bannerArr{
self.imgeArr=bannerArr;
[self initView];
}
-(void)setHomebanner:(NSString *)homebanner{
//VC中viewwilldisappear时取消定时器
if(self.headerScroll && [homebanner isEqualToString:@""]){
if ([self.timer isValid]) {
[self.timer invalidate];
self.timer = nil;
NSLog(@"View消失");
}
[self.headerScroll setContentOffset:CGPointZero animated:YES];//首页消失时吧轮播置为初始位置
}
//viewwillappear时开启定时器
if(self.headerScroll &&[homebanner isEqualToString:@"willappear"]){
NSLog(@"view 出现");
if(!self.timer && !self.timer.isValid){
[self NSTimers];
}
}
}
@end
**************在VC中
-(void)viewWillDisappear:(BOOL)animated{
[superviewWillDisappear:animated];
if(self.innerAdvertiseView){
self.innerAdvertiseView.homebanner=@"";//关闭定时器吧轮播置为0;
}
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
if(self.innerAdvertiseView){
self.innerAdvertiseView.homebanner=@"willappear";//开启轮播;
}
}
==================2.collectionview实现轮播
#import "CZLoopImagesController.h"
#import "CZLoopImagesCell.h"
#import "CZHeadline.h"
@interface CZLoopImagesController ()
@property (nonatomic,strong)NSArray *headlines;
@property (weak,nonatomic)IBOutletUICollectionViewFlowLayout *layout;
@end
@implementation CZLoopImagesController
static NSString *const reuseIdentifier =@"image";
- (void)viewDidLoad {
[superviewDidLoad];
//1 发送异步请求,获取数据
[CZHeadlineheadlinesWithSuccess:^(NSArray *array) {
self.headlines = array;
//刷新collectionView
[self.collectionViewreloadData];
//无限轮播---2 当界面刷新完成,跳转到第二组
//第二组的第一个cell
NSIndexPath *path = [NSIndexPathindexPathForItem:0inSection:1];
[self.collectionViewscrollToItemAtIndexPath:pathatScrollPosition:0animated:NO];
} errorBlock:^(NSError *e) {
NSLog(@"%@",e);
}];
//2 设置layout
self.layout.itemSize =self.collectionView.bounds.size;
self.layout.minimumInteritemSpacing =0;
self.layout.minimumLineSpacing =0;
self.layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//3 设置collectionView
self.collectionView.pagingEnabled =YES;
self.collectionView.bounces =NO;
// self.collectionView.showsHorizontalScrollIndicator = NO;
}
#pragma mark <UICollectionViewDataSource>
//无限轮播---1 设置组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return3;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return self.headlines.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CZLoopImagesCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
//记录页码
cell.tag = indexPath.item;
NSLog(@"--item--%tu",indexPath.item);
NSLog(@"--row--%tu",indexPath.row);
NSLog(@"--section--%tu",indexPath.section);
//赋值
cell.headline =self.headlines[indexPath.item];
// NSLog(@"%zd",indexPath.item);
return cell;
}
//collectionView的代理方法
//手指控制结束滚动的时候执行------减速停止的时候调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//无限轮播---4 计算当前显示的是第几个cell
int offsetX = scrollView.contentOffset.x / scrollView.bounds.size.width;
int index = offsetX %4;
NSLog(@"offsetX : %d index : %d",offsetX,index);
//无限轮播---3 滚动结束之后,滚动到第二组
NSIndexPath *path = [NSIndexPathindexPathForItem:indexinSection:1];
[self.collectionViewscrollToItemAtIndexPath:pathatScrollPosition:0animated:YES];
}
================3.
#import "SPBannersView.h"
#import "SPBanner.h"
@interface SPBannersView ()<UIScrollViewDelegate>
@property (strong,nonatomic)NSMutableArray *imageArray;
@property (assign,nonatomic)NSInteger currentPage;//当前页码
@property (strong,nonatomic)UIScrollView *bannerView;
@property (strong,nonatomic)UIPageControl *pageControl;
@property (strong,nonatomic)NSTimer *timer;
@end
@implementation SPBannersView
-(void)dealloc{
[self.timerinvalidate];
self.timer =nil;
}
-(instancetype)initWithFrame:(CGRect)frame{
if(self = [superinitWithFrame:frame])
{
[selfinitSubViews];
}
returnself;
}
/**
* 初始化界面元素
*/
-(void)initSubViews{
//init the banner view
self.bannerView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,0,self.bounds.size.width,self.bounds.size.height)];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bannerViewTapped)];
[self.bannerView addGestureRecognizer:tapGesture];
self.bannerView.pagingEnabled =YES;
self.bannerView.showsVerticalScrollIndicator = NO;
self.bannerView.showsHorizontalScrollIndicator = NO;
self.bannerView.delegate =self;
//add the page control
self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0,self.bounds.size.height -20, self.bounds.size.width,20)];
self.pageControl.numberOfPages =0;
self.pageControl.currentPage =0;
self.pageControl.userInteractionEnabled = NO;
//self.pageControl.backgroundColor = [UIColor colorWithRGB:0xeaedf1 alpha:0.5];// ColorViewBackground;
[selfaddSubview:self.bannerView];
[selfaddSubview:self.pageControl];
}
/**
* 点击事件
*/
- (void)bannerViewTapped {
//返回当前点击的图片数组的索引
if(self.delegate && [self.delegaterespondsToSelector:@selector(SPBannersView:selectedIndex:)]){
[self.delegateSPBannersView:selfselectedIndex:self.currentPage];
}
}
-(void)setBanners:(NSArray *)banners{
if(!banners || banners.count <=0){
return;
}
_banners = banners;
//重新将数据源进行一次赋值
if(!self.timer){
self.timer = [NSTimerscheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(timerFire)userInfo:nil
repeats:YES];
}
NSInteger count =_banners.count;
self.pageControl.numberOfPages = count;
if(!self.imageArray)
{
self.imageArray = [NSMutableArrayarray];
}
[self.imageArrayremoveAllObjects];
if(self.isLocalPic)
{
for (int i =0; i < count; i++)
{
NSString *imgName =_banners[i];
[self.imageArray addObject:imgName];
}
}
else
{
for (int i =0; i < count; i++)
{
SPBanner *banner =_banners[i];
NSURL *url = [NSURL URLWithString:banner.bannerImgUrl];
[self.imageArray addObject:url];
}
}
self.bannerView.contentSize =CGSizeMake(self.bounds.size.width * count, self.bounds.size.height);
[self addImageView];
}
- (void)timerFire {
CGPoint offset =self.bannerView.contentOffset;
offset.x +=self.bounds.size.width;
[self.bannerView setContentOffset:offsetanimated:YES];
}
//自定义方法
/**
* 添加网络图片
*/
- (void)addImageView
{
CGFloat selfWidth =self.bounds.size.width;
CGFloat selfHeight =self.bounds.size.height;
//移除所有子元素
[self.bannerView.subviewsmakeObjectsPerformSelector:@selector(removeFromSuperview)];
if(self.imageArray.count ==0)return;
//上一个图片索引
NSInteger prePage = [selfgetPage:self.currentPage -1];
//下一个图片索引
NSInteger nextPage = [selfgetPage:self.currentPage +1];
//上一张图片
if (prePage>self.imageArray.count-1||prePage<0) {
return;
}
if(_isLocalPic)
{
//显示本地图片
NSString *preImageUrl = [self.imageArrayobjectAtIndex:prePage];
//当前的图片
if (self.currentPage>self.imageArray.count-1||self.currentPage<0) {
return;
}
NSString *currentImageUrl = [self.imageArrayobjectAtIndex:self.currentPage];
//下一张图片
NSString *nextImageUrl = [self.imageArrayobjectAtIndex:nextPage];
//上一张图片视图
UIImageView *preImageView = [[UIImageViewalloc]initWithFrame:CGRectMake(0,0, selfWidth, selfHeight)];
preImageView.image = [UIImageimageNamed:preImageUrl];
[self.bannerViewaddSubview:preImageView];
//当前图片视图
UIImageView *currentImageView = [[UIImageView alloc]initWithFrame:CGRectMake(selfWidth,0, selfWidth, selfHeight)];
currentImageView.image = [UIImage imageNamed:currentImageUrl];
[self.bannerView addSubview:currentImageView];
//下一张图片视图
UIImageView *nextImageView = [[UIImageView alloc]initWithFrame:CGRectMake(2 * selfWidth,0, selfWidth, selfHeight)];
nextImageView.image = [UIImage imageNamed:nextImageUrl];
[self.bannerView addSubview:nextImageView];
}
else
{
//显示网络图片
NSURL *preImageUrl = [self.imageArrayobjectAtIndex:prePage];
//当前的图片
if (self.currentPage>self.imageArray.count-1||self.currentPage<0) {
return;
}
NSURL *currentImageUrl = [self.imageArrayobjectAtIndex:self.currentPage];
//下一张图片
NSURL *nextImageUrl = [self.imageArrayobjectAtIndex:nextPage];
//上一张图片视图
UIImageView *preImageView = [[UIImageViewalloc]initWithFrame:CGRectMake(0,0, selfWidth, selfHeight)];
UIImage *image = [UIImageimageNamed:@"icon_banner_null"];
[preImageView sd_setImageWithURL:preImageUrlplaceholderImage:image];
[self.bannerViewaddSubview:preImageView];
//当前图片视图
UIImageView *currentImageView = [[UIImageViewalloc]initWithFrame:CGRectMake(selfWidth,0, selfWidth, selfHeight)];
[currentImageView sd_setImageWithURL:currentImageUrlplaceholderImage:image];
[self.bannerViewaddSubview:currentImageView];
//下一张图片视图
UIImageView *nextImageView = [[UIImageViewalloc]initWithFrame:CGRectMake(2 * selfWidth,0, selfWidth, selfHeight)];
[nextImageView sd_setImageWithURL:nextImageUrlplaceholderImage:image];
[self.bannerViewaddSubview:nextImageView];
}
//设置从中间图片显示
self.bannerView.contentOffset =CGPointMake(selfWidth,0);
}
- (NSInteger)getPage:(NSInteger)page
{
//如果索引<0,取得最后一个索引
if (page <0) {
page = [self.imageArraycount] -1;
}elseif (page >= [self.imageArraycount]) {
//如果索引>=当前总数,索引从0开始
page = 0;
}
return page;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if(scrollView ==self.bannerView) {
//得到当前的contenOffset.x
CGFloat x = scrollView.contentOffset.x;
//如果x>=640的时候,加入下3张图片
if (x >=self.bounds.size.width *2) {
_currentPage = [self getPage:_currentPage +1];
[selfaddImageView];
} elseif (x <=0){ //当x<=0的时候,加入上3张图片
_currentPage = [self getPage:_currentPage -1];
[selfaddImageView];
}
//改变分页控制当前的页数
_pageControl.currentPage =_currentPage;
}
}
@end
*******当前页面切换collectionviewcell显示个数
#importNS_ASSUME_NONNULL_BEGIN@interface HYVideovc : UIViewController@endNS_ASSUME_NONNULL_END*******import "HYVideovc.h"#import "HYVideocolleccell.h"@interface HYVideovc () @property(nonatomic,weak)UIButton *onebtn;@property(nonatomic,weak)UIButton *twobtn;@property(nonatomic,weak)UIButton *threebtn;@property(nonatomic,weak)UIButton *fourbtn;@property(nonatomic,weak) UILabel *centerlabel;@property(nonatomic,assign)NSInteger rowCount;//每一行显示的个数@property(nonatomic,assign)NSInteger cellCount;//cell的总个数@property(nonatomic,assign)NSInteger pageNum;//第几页@property(nonatomic,assign)NSInteger pagetotalNum;//总共几页@property(nonatomic,weak)UICollectionView *collec;@property(nonatomic,weak)UICollectionViewFlowLayout *flowlayout;@property(nonatomic,strong)NSMutableArray *changebtnarr;@endstatic NSString *identifier=@"HYVideocolleccell";@implementation HYVideovc-(NSMutableArray *)changebtnarr{ if(nil==_changebtnarr){ _changebtnarr=[[NSMutableArray alloc]initWithCapacity:5];; } return _changebtnarr;}- (void)viewDidLoad { [super viewDidLoad]; [self initViews];}-(void)initViews{ self.view.backgroundColor=[UIColor colorWithWhite:0.6 alpha:0.6]; UIView *changeview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 30)]; changeview.backgroundColor=[UIColor blueColor]; [self.navigationController.navigationBar addSubview:changeview]; changeview.center=CGPointMake(self.view.center.x, TopSpaceHigh-44); UIButton *leftbtn=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 30)]; [leftbtn setTitle:@"预览" forState:UIControlStateNormal]; [leftbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [leftbtn addTarget:self action:@selector(leftbtnclcik:) forControlEvents:UIControlEventTouchUpInside]; [changeview addSubview:leftbtn]; UIButton *rightbtn=[[UIButton alloc]initWithFrame:CGRectMake(50, 0, 50, 30)]; [rightbtn setTitle:@"回放" forState:UIControlStateNormal]; [rightbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [rightbtn addTarget:self action:@selector(rightbtnbtnclcik:) forControlEvents:UIControlEventTouchUpInside]; [changeview addSubview:rightbtn]; // UIView* selectcameraPoint=[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];// [self.view addSubview:selectcameraPoint];// UILabel *leftlabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 50)];// leftlabel.text=@"选择监控点";// [selectcameraPoint addSubview:leftlabel]; self.cellCount=16; self.rowCount=2; UICollectionViewFlowLayout *flowlayout=[[UICollectionViewFlowLayout alloc]init]; self.flowlayout=flowlayout; flowlayout.itemSize=CGSizeMake(WIDTH/self.rowCount-0.5, WIDTH/self.rowCount-0.5); flowlayout.minimumLineSpacing=1; flowlayout.minimumInteritemSpacing=0; flowlayout.scrollDirection=UICollectionViewScrollDirectionHorizontal; UICollectionView *collec=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 50, WIDTH, WIDTH) collectionViewLayout:flowlayout]; self.collec=collec; collec.delegate=self; collec.dataSource=self; collec.backgroundColor=[UIColor whiteColor]; collec.pagingEnabled=YES; [self.view addSubview:collec]; [collec registerClass:[HYVideocolleccell class] forCellWithReuseIdentifier:identifier]; UIView *btnview=[[UIView alloc]initWithFrame:CGRectMake(0, HEIGHT-BottomHeight-TopSpaceHigh-120, WIDTH, 50)]; btnview.backgroundColor=[UIColor blueColor]; [self.view addSubview:btnview]; UIButton *onebtn=[[UIButton alloc]initWithFrame:CGRectMake(10, 10, 30, 30)]; self.onebtn=onebtn; onebtn.tag=11; [onebtn setTitle:@"1" forState:UIControlStateNormal]; [onebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [onebtn addTarget:self action:@selector(changgeBtn:) forControlEvents:UIControlEventTouchUpInside]; [btnview addSubview:onebtn]; UIView *firstsepline=[[UIView alloc]initWithFrame:CGRectMake(50, 5, 1, 40)]; firstsepline.backgroundColor=[UIColor colorWithWhite:0.6 alpha:0.6]; [btnview addSubview:firstsepline]; UIButton *twobtn=[[UIButton alloc]initWithFrame:CGRectMake(60, 10, 30, 30)]; self.twobtn=twobtn; twobtn.tag=12; [twobtn setTitle:@"4" forState:UIControlStateNormal]; [twobtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [twobtn setBackgroundColor:[UIColor blackColor]]; [twobtn addTarget:self action:@selector(changgeBtn:) forControlEvents:UIControlEventTouchUpInside]; [btnview addSubview:twobtn]; UILabel *centerlabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 10, 50, 30)]; self.centerlabel=centerlabel; centerlabel.text=@"1/4"; centerlabel.centerx=btnview.centerx; [btnview addSubview:centerlabel]; UIButton *threebtn=[[UIButton alloc]initWithFrame:CGRectMake(WIDTH-90, 10, 30, 30)]; self.threebtn=threebtn; threebtn.tag=13; [threebtn setTitle:@"9" forState:UIControlStateNormal]; [threebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [threebtn addTarget:self action:@selector(changgeBtn:) forControlEvents:UIControlEventTouchUpInside]; [btnview addSubview:threebtn]; UIView *secsepline=[[UIView alloc]initWithFrame:CGRectMake(WIDTH-50, 5, 1, 40)]; secsepline.backgroundColor=[UIColor colorWithWhite:0.6 alpha:0.6]; [btnview addSubview:secsepline]; UIButton *fourbtn=[[UIButton alloc]initWithFrame:CGRectMake(WIDTH-40, 10, 30, 30)]; self.fourbtn=fourbtn; fourbtn.tag=14; [fourbtn setTitle:@"16" forState:UIControlStateNormal]; [fourbtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [fourbtn addTarget:self action:@selector(changgeBtn:) forControlEvents:UIControlEventTouchUpInside]; [btnview addSubview:fourbtn]; [self.changebtnarr addObject:onebtn]; [self.changebtnarr addObject:twobtn]; [self.changebtnarr addObject:threebtn]; [self.changebtnarr addObject:fourbtn];}-(void)changgeBtn:(UIButton *)btn{ NSInteger stag=btn.tag-10; NSLog(@"按钮---%ld--%lu",(long)stag,(unsigned long)self.changebtnarr.count); [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [btn setBackgroundColor:[UIColor blackColor]]; if(btn==self.onebtn){ [self.twobtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.twobtn setBackgroundColor:[UIColor whiteColor]]; [self.threebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.threebtn setBackgroundColor:[UIColor whiteColor]]; [self.fourbtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.fourbtn setBackgroundColor:[UIColor whiteColor]]; }else if(btn==self.twobtn){ [self.onebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.onebtn setBackgroundColor:[UIColor whiteColor]]; [self.threebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.threebtn setBackgroundColor:[UIColor whiteColor]]; [self.fourbtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.fourbtn setBackgroundColor:[UIColor whiteColor]]; }else if(btn==self.threebtn){ [self.onebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.onebtn setBackgroundColor:[UIColor whiteColor]]; [self.twobtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.twobtn setBackgroundColor:[UIColor whiteColor]]; [self.fourbtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.fourbtn setBackgroundColor:[UIColor whiteColor]]; }else if(btn==self.fourbtn){ [self.onebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.onebtn setBackgroundColor:[UIColor whiteColor]]; [self.twobtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.twobtn setBackgroundColor:[UIColor whiteColor]]; [self.threebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.threebtn setBackgroundColor:[UIColor whiteColor]]; } if(stag==1){ self.cellCount=16; self.rowCount=1; self.centerlabel.text=@"1/16"; [self.collec reloadData]; }else if(stag==2){ self.cellCount=16; self.rowCount=2; self.centerlabel.text=@"1/4"; [self.collec reloadData]; }else if(stag==3){ self.cellCount=18; self.rowCount=3; self.centerlabel.text=@"1/2"; [self.collec reloadData]; }else if(stag==4){ self.cellCount=16; self.rowCount=4; self.centerlabel.text=@"1/1"; [self.collec reloadData]; } self.flowlayout.itemSize=CGSizeMake(WIDTH/self.rowCount-0.5, WIDTH/self.rowCount-0.5);}-(void)rightbtnbtnclcik:(UIButton *)btn{ NSLog(@"回放");}-(void)leftbtnclcik:(UIButton *)btn{ NSLog(@"预览");}-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ NSLog(@"刷新组"); return 1;}-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ NSLog(@"刷新row"); return self.cellCount;}-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ NSLog(@"刷新cell"); HYVideocolleccell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; return cell;}-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{ }-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ NSInteger x= scrollView.contentOffset.x; NSInteger pagenum=x/WIDTH+1; NSInteger totalnum=self.cellCount/(self.rowCount*self.rowCount); NSLog(@"停止滚动--%ld",(long)x); self.centerlabel.text=[NSString stringWithFormat:@"%ld/%ld",(long)pagenum,totalnum];}@end******#import NS_ASSUME_NONNULL_BEGIN@interface HYVideocolleccell : UICollectionViewCell@endNS_ASSUME_NONNULL_END*****#import "HYVideocolleccell.h"@implementation HYVideocolleccell-(instancetype)initWithFrame:(CGRect)frame{ if(self=[super initWithFrame:frame]){ [self initViews]; } return self;}-(void)initViews{ self.backgroundColor=[UIColor blackColor];}@end
定时器和手动拖拽scrollview的冲突:
主线程的 RunLoop 里有两个预置的 Mode:kCFRunLoopDefaultMode 和 UITrackingRunLoopMode。这两个 Mode 都已经被标记为"Common"属性。DefaultMode 是 App 平时所处的状态,TrackingRunLoopMode 是追踪 ScrollView 滑动时的状态。当你创建一个 Timer 并加到 DefaultMode 时,Timer 会得到重复回调,但此时滑动一个TableView时,RunLoop 会将 mode 切换为 TrackingRunLoopMode,这时 Timer 就不会被回调,不会影响到滑动操作。
有时希望滑动和定时器调用互不影响,就需要一个 Timer在两个 Mode 中都能得到回调。一种办法就是将这个 Timer 分别加入这两个 Mode;还有一种方式就是将 Timer 加入到顶层的 RunLoop 的 "commonModeItems" 中,"commonModeItems" 会被 RunLoop 自动更新到所有具有"Common"属性的 Mode 里去。
转载地址:http://gqlgi.baihongyu.com/