iOS 轮播图的实现scrollView

来源:互联网 发布:知无涯者 台词 编辑:程序博客网 时间:2024/05/16 08:44
前言 : 因为看到技术文章有很多关于轮播图的实现,可是并没有想象中的那么的实现简单,于是自己写一个当作以后的笔记。加深印象

图片发自简书App

有对轮播图实现原理不清楚的朋友可以自行百度也可以看下这篇文章。本文不做赘述(ps通过scroll来实现轮播效果)。
直接进入正文
  • 假设 scrollview展示三个View 红 黄 蓝, 为了实现无限轮播需求,我们可以最左边加个 蓝 右边加个红 用于循环
    创建代码如下
NSArray *colorArray = @[[UIColor blueColor],[UIColor redColor],[UIColor yellowColor],[UIColor blueColor],[UIColor redColor]];    self.colorsArray = [NSArray arrayWithArray:colorArray]; ```这里用到了for循环创建

for (int i = 0; i < colorArray.count; i++) {

    UIView *view = [[UIView alloc] init];    view.backgroundColor = colorArray[i];    view.frame = CGRectMake(i*CGRectGetWidth(self.view.frame), 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(_myscrollView.frame));    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];    lable.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, CGRectGetHeight(_myscrollView.frame)/2 - 15);    [lable setFont:[UIFont systemFontOfSize:21]];    lable.textAlignment = NSTextAlignmentCenter;    lable.text = [NSString stringWithFormat:@"%d",i];    [view addSubview:lable];    [_myscrollView addSubview:view];}_myscrollView.pagingEnabled = YES;_myscrollView.showsHorizontalScrollIndicator = NO;_myscrollView.contentSize = CGSizeMake(colorArray.count*CGRectGetWidth(self.view.frame), 0);_myscrollView.contentOffset = CGPointMake(CGRectGetWidth(self.view.frame), 0);_myscrollView.bounces = NO;

[self addTimer];

当然了无限滚动还需要一个定时器创建

(void)addTimer
{
if (self.timer)return;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(runImage) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

再来一个移除

(void)invalidateTimer
{
[self.timer invalidate];

self.timer = nil;

}

定时器开启,走方法,管控轮播

(void)runImage
{
CGPoint apoint = self.myscrollView.contentOffset;
[self.myscrollView setContentOffset:CGPointMake(apoint.x+CGRectGetWidth(self.view.frame), 0) animated:YES];
}

定时器 以动画形式改变scrollview的contentOffset 调用

(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
NSLog(@”endani”);
if (scrollView.contentOffset.x==0) {
[scrollView setContentOffset:CGPointMake(CGRectGetWidth(self.view.frame)*(self.colorsArray.count-2), 0)];
}else if (scrollView.contentOffset.x==scrollView.contentSize.width-CGRectGetWidth(self.view.frame)){
[scrollView setContentOffset:CGPointMake(CGRectGetWidth(self.view.frame), 0)];
}
}
“`
当然免不了测试人员会拖拽
开始拖拽(关闭定时器)

 (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{    [self invalidateTimer];}

结束拖拽(开启定时器)

(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{    NSLog(@"enddra");    [self addTimer];}
这样就实现了一个简单的轮播图,当然对于数据量大的轮播来说,还是用collection实现为好。有时间我会再写一个collection实现轮播的方式,最后Demo地址
原创粉丝点击