iOS开发-UIScrollView图片无限循环

十度 IOS 2015年12月01日 收藏

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

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

  1. -(UIPageControl *)pageControl{
  2. if (!_pageControl) {
  3. _pageControl=[[UIPageControl alloc]initWithFrame:CGRectMake(0, 0, 150, 40)];
  4. _pageControl.currentPage=0;
  5. _pageControl.pageIndicatorTintColor=[UIColor whiteColor];
  6. _pageControl.currentPageIndicatorTintColor=[UIColor greenColor];
  7. }
  8. return _pageControl;
  9. }
  10. -(UIScrollView *)scrollView{
  11. if (!_scrollView) {
  12. CGRect screenRect=[[UIScreen mainScreen]bounds];
  13. _scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, CGRectGetWidth(screenRect), CGRectGetHeight(screenRect)-164)];
  14. [_scrollView setBounces:NO];
  15. [_scrollView setShowsHorizontalScrollIndicator:NO];
  16. [_scrollView setPagingEnabled:YES];
  17. _scrollView.delegate=self;
  18. }
  19. return _scrollView;
  20. }

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

  1. self.screenRect=[[UIScreen mainScreen]bounds];
  2. CGFloat width=self.scrollView.bounds.size.width;
  3. CGFloat height=self.scrollView.bounds.size.height;
  4. self.imageArr=@[@"girl0.jpg",@"girl1.jpg",@"girl2.jpg"];
  5. [self.scrollView setContentSize:CGSizeMake([self.imageArr count]*width, height)];
  6.  
  7. for (NSInteger i=0; i<[self.imageArr count]; i++) {
  8. UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(i*width, 0, width,height)];
  9. imageView.image=[UIImage imageNamed:self.imageArr[i]];
  10. imageView.contentMode=UIViewContentModeScaleToFill;
  11. [self.scrollView addSubview:imageView];
  12. }
  13. [self.view addSubview:self.scrollView];
  14. self.pageControl.numberOfPages=[self.imageArr count];
  15. self.pageControl.center=CGPointMake(self.scrollView.center.x, CGRectGetMaxY(self.scrollView.bounds)+50);
  16. [self.view addSubview:self.pageControl];
  17. self.pageLabel.text=[NSString stringWithFormat:@"%d/%lu",1,[self.imageArr count]];
  18. [self.view addSubview:self.pageLabel];

实现UIScrollViewDelegate中scrollViewDidEndDecelerating的方法:

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

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