> IOS开发在线手册 > iOS开发-UIScrollView图片无限循环

关于UIScrollView图片浏览的例子有很多,之前也写过类似方面的文章,关于UIScrollView的图片循环在新闻类的App基本上是比较常见的一种情况就是图片浏览,然后根据不同的图片显示不同的内容显示不同的图片的介绍,因为属于比较常用的空间,先来看下需要实现的效果:

iOS开发-UIScrollView图片无限循环

小圆点指示器是通过UIPageControl实现的,图片循环通过UIScrollView实现:

-(UIPageControl *)pageControl{
    if (!_pageControl) {
        _pageControl=[[UIPageControl alloc]initWithFrame:CGRectMake(0, 0, 150, 40)];
        _pageControl.currentPage=0;
        _pageControl.pageIndicatorTintColor=[UIColor whiteColor];
        _pageControl.currentPageIndicatorTintColor=[UIColor greenColor];
    }
    return _pageControl;
}
-(UIScrollView *)scrollView{
    if (!_scrollView) {
        CGRect   screenRect=[[UIScreen mainScreen]bounds];
        _scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, CGRectGetWidth(screenRect), CGRectGetHeight(screenRect)-164)];
        [_scrollView setBounces:NO];
        [_scrollView setShowsHorizontalScrollIndicator:NO];
        [_scrollView setPagingEnabled:YES];
        _scrollView.delegate=self;
    }
    return _scrollView;
}

关于分页的页面配置以及页数Label的设置:

    self.screenRect=[[UIScreen mainScreen]bounds];
    CGFloat width=self.scrollView.bounds.size.width;
    CGFloat height=self.scrollView.bounds.size.height;
    self.imageArr=@[@"girl0.jpg",@"girl1.jpg",@"girl2.jpg"];
    [self.scrollView setContentSize:CGSizeMake([self.imageArr count]*width, height)];

    for (NSInteger i=0; i<[self.imageArr count]; i++) {
        UIImageView  *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(i*width, 0, width,height)];
        imageView.image=[UIImage imageNamed:self.imageArr[i]];
        imageView.contentMode=UIViewContentModeScaleToFill;
        [self.scrollView  addSubview:imageView];
    }
    [self.view addSubview:self.scrollView];
    
    self.pageControl.numberOfPages=[self.imageArr count];
    self.pageControl.center=CGPointMake(self.scrollView.center.x, CGRectGetMaxY(self.scrollView.bounds)+50);
    [self.view addSubview:self.pageControl];
    self.pageLabel.text=[NSString stringWithFormat:@"%d/%lu",1,[self.imageArr count]];
    [self.view addSubview:self.pageLabel];

实现UIScrollViewDelegate中scrollViewDidEndDecelerating的方法:

//博客园-FlyElephant 原文地址:Http://www.cnblogs.com/xiaofeixiang/
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (self.currentPage==[self.imageArr count]-1) {
        self.currentPage=0;
        self.scrollView.contentOffset=CGPointMake(0, 0);
    }else{
       self.currentPage=scrollView.contentOffset.x/CGRectGetWidth(self.screenRect);
    }
    self.pageControl.currentPage=self.currentPage;
    [self.pageLabel setText:[NSString stringWithFormat:@"%ld/%lu",self.currentPage+1,[self.imageArr count]]];
}

 简单的UIScrollView实现基本上ok了,当然关于UIScrollView根据不同场景去实现不同的功能代码量比这肯定更复杂~