1 // 2 // ViewController.m 3 // 09-pageControl 4 // 5 // Created by wangAngelo on 11/30/15. 6 // Copyright © 2015 angelowang. All rights reserved. 7 // 8 9 #import "ViewController.h" 10 11 @interface ViewController () <UIScrollViewDelegate> 12 @property (weak, nonatomic) IBOutlet UIScrollView *scrollView; 13 @property (weak, nonatomic) IBOutlet UIPageControl *pageControl; 14 @property (nonatomic, strong) NSTimer *timer; 15 @end 16 17 @implementation ViewController 18 19 - (void)viewDidLoad { 20 [super viewDidLoad]; 21 // Do any additional setup after loading the view, typically from a nib. 22 self.scrollView.delegate = self; 23 24 /** 25 * scrollView中图片轮播部分 26 */ 27 CGFloat imagesW = self.scrollView.bounds.size.width; 28 CGFloat imagesH = self.scrollView.bounds.size.height; 29 /** 30 * 设置图片数量和图片的总宽度 31 */ 32 int imagesCount = 5; 33 CGFloat totalImageWidth = imagesCount * imagesW; 34 35 /** 36 * 把每个图片的imageView加到ScrollView上 37 */ 38 for (int i = 0; i < imagesCount; i++) { 39 UIImageView *images = [[UIImageView alloc] init]; 40 CGFloat imagesX = i * imagesW; 41 CGFloat imagesY = 0; 42 images.frame = CGRectMake(imagesX, imagesY, imagesW, imagesH); 43 images.image = [UIImage imageNamed:[NSString stringWithFormat:@"img_%02d",i + 1]]; 44 [self.scrollView addSubview:images]; 45 } 46 /** 47 * 设置ScrollView可以滚动的范围 48 */ 49 self.scrollView.contentSize = CGSizeMake(totalImageWidth, 0); 50 /** 51 * 是否可以纵向滚动 否 52 */ 53 self.scrollView.showsHorizontalScrollIndicator = NO; 54 /** 55 * 是否单页滚动 56 */ 57 self.scrollView.pagingEnabled = YES; 58 59 /** 60 * pageControl部分 61 * 62 */ 63 self.pageControl.numberOfPages = imagesCount; 64 /** 65 * 定时器部分 66 * 67 */ 68 [self addTimer]; 69 70 } 71 72 /** 73 * 添加定时器 74 */ 75 - (void)addTimer { 76 self.timer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(nextPage) userInfo:nil repeats:YES]; 77 [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; 78 } 79 80 /** 81 * 移除定时器 82 */ 83 - (void)removeTimer { 84 [self.timer invalidate]; 85 self.timer = nil; 86 } 87 88 #pragma mark - 代理方法 89 90 - (void)scrollViewDidScroll:(UIScrollView *)scrollView { 91 CGFloat imagesW = self.scrollView.bounds.size.width; 92 /** 93 * 判断翻页状态 94 */ 95 int page = (int)round(self.scrollView.contentOffset.x / imagesW); 96 self.pageControl.currentPage = page; 97 } 98 99 -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { 100 [self removeTimer]; 101 } 102 103 -(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { 104 [self addTimer]; 105 } 106 107 - (void)nextPage { 108 109 int page = 0; 110 if (self.pageControl.currentPage != 4) { 111 page = (int)self.pageControl.currentPage + 1; 112 } else { 113 page = 0 ; 114 } 115 CGFloat imagesW = self.scrollView.bounds.size.width; 116 CGFloat offsetX = imagesW * page; 117 [self.scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES]; 118 } 119 120 @end