图片轮播器
#import "ViewController.h"
#define ImageCount 5
@interface ViewController ()<UIScrollViewDelegate>
{
NSTimer * timer;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageConterl;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//固定的尺寸参数
CGFloat imageW = self.scrollView.frame.size.width;
CGFloat imageH = self.scrollView.frame.size.height;
CGFloat imageY = 0;
for (int i = 0;i<ImageCount; i++) {
UIImageView *imageView = [[UIImageView alloc] init];
//设置图片尺寸
CGFloat imageX = i * imageW;
imageView.frame = CGRectMake(imageX, imageY, imageW, imageH);
//图片显示
imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"img_%02d",i + 1]];
[self.scrollView addSubview:imageView];
}
//设置contentSize
self.scrollView.contentSize = CGSizeMake(ImageCount * imageW, 0);
//隐藏水平滚动条
self.scrollView.showsHorizontalScrollIndicator = NO;
//分页浏览
self.scrollView.pagingEnabled = YES;
//设置page的总数
self.pageConterl.numberOfPages = ImageCount;
//添加定时器
[self addTimer];
}
//添加定时器
-(void)addTimer
{
timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changImage) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
//移除定时器
-(void)removeTimer
{
[timer invalidate];
timer = nil;
}
//改变页码
-(void)changImage
{
//增加pageControl的页码
long page = 0;
if (self.pageConterl.currentPage == ImageCount -1) {
page = 0 ;
}else{
page = self.pageConterl.currentPage + 1;
}
//计算scrollView滚动的位置
CGFloat offsetX = page * self.scrollView.frame.size.width;
CGPoint offset = CGPointMake(offsetX, 0);
[self.scrollView setContentOffset:offset animated:YES];
}
//scrollView正在滚动就会调用
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//根据scrollView的滚动位置聚丁pageControl显示第几页
CGFloat scrollW = scrollView.frame.size.width;
int page = (scrollView.contentOffset.x +scrollW*0.5)/scrollW;
self.pageConterl.currentPage = page;
}
//开始拖拽时使用
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[self removeTimer];
}
//停止拖拽时使用
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
[self addTimer];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end