这是图片轮播器代码的实现 ,如有不足 望指教
#import "CZQViewController.h"
#define ImageCount 5
@interface CZQViewController()<UIScrollViewDelegate>
/**
* scrollView属性
*/
@property (weak, nonatomic) IBOutlet UIScrollView*scrollView;
/**
* pagingNum
*/
@property (weak, nonatomic) IBOutlet UIPageControl*pageControl;
/**
* 创建定时器
*/
@property(nonatomic,strong)NSTimer *timer;
@end
@implementationCZQViewController
- (void)viewDidLoad
{
[super viewDidLoad];
CGFloat imageW=self.scrollView.frame.size.width;
CGFloat imageH=self.scrollView.frame.size.height;
//实现图片的轮播
for (int i=1; i<ImageCount+1; i++) {
UIImageView *imageView= [[UIImageView alloc] init];
CGFloat imageY=0;
CGFloat imageX=(i-1)*imageW;
imageView.frame=CGRectMake(imageX,imageY, imageW, imageH);
//添加图片
imageView.image=[UIImage imageNamed:[NSString stringWithFormat:@"img_%02d",i]];
[self.scrollView addSubview:imageView];
}
//添加滚动范围
self.scrollView.contentSize=CGSizeMake(ImageCount*imageW, 0);
//半页后自动滚动
self.scrollView.pagingEnabled=YES;
//总共页数
self.pageControl.numberOfPages=ImageCount;
//设置代理
self.scrollView.delegate=self;
[self addScrollTimer];
}
//设置定时器
- (void)addScrollTimer{
// 创建定时器
self.timer=[NSTimer timerWithTimeInterval:2.0f target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
//兼容两种模式的运行
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
//结束定时
- (void)endScrollTimer{
[self.timer invalidate];
self.timer = nil;
}
/**
* 下一页
*/
- (void)nextPage{
int currentPage=self.pageControl.currentPage;
currentPage++;
if (currentPage==5) {
currentPage=0;
}
CGFloat width=self.scrollView.frame.size.width;
//计算偏移量
CGPoint offset=CGPointMake(currentPage*width, 0.f);
[UIView animateWithDuration:.2f animations:^{
self.scrollView.contentOffset=offset;
}];
}
#pragma mark - 代理的方法
/**
* 滚动时执行的方法
*/
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGPoint offset=self.scrollView.contentOffset;
CGFloat offsetX=offset.x;
CGFloat width=self.scrollView.frame.size.width;
int pageNum=(offsetX+0.5*width)/width;
self.pageControl.currentPage=pageNum;
}
/**
* 开始拖拽时执行的方法
*/
- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView{
[self endScrollTimer];
}
/**
* 拖拽执行完后的方法
*/
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollViewwillDecelerate:(BOOL)decelerate{
//开启时间定时
[self addScrollTimer];
}
@end
实现后的图片效果如下