一提到轮播图,我们很多人会用scrollView进行处理,我们可以利用contentoffsize属性对显示窗口进行设置。
- (void)viewDidLoad {
[super viewDidLoad];
scrollViewDemo=[[UIScrollView alloc]initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height/2)];
scrollViewDemo.backgroundColor=[UIColor whiteColor];
[self.view addSubview:scrollViewDemo];
pageControl=[[UIPageControl alloc]initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width-200)/2, scrollViewDemo.frame.size.height-60, 200, 60)];
// 图片的个数
count=4;
dataSource=@[@"demo1",@"demo2",@"demo3",@"demo4"];
// 获得scrollView的宽度
CGFloat width=scrollViewDemo.frame.size.width;
//添加图片到ScrollView
for (int i=0; i<dataSource.count; i++) {
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(i*width, 0, width, scrollViewDemo.frame.size.height)];
imageView.image=[UIImage imageNamed:dataSource
[i]];
[scrollViewDemo addSubview:imageView];
}
scrollViewDemo.contentSize=CGSizeMake(count*width, 0);
//图片的个数,指示器的颜色
pageControl.numberOfPages=count;
pageControl.pageIndicatorTintColor=[UIColor whiteColor];
pageControl.currentPageIndicatorTintColor=[UIColor blueColor];
//分页的格式,水平滚动条
scrollViewDemo.pagingEnabled=YES;
scrollViewDemo.showsHorizontalScrollIndicator=NO;
scrollViewDemo.delegate=self;
[self.view addSubview:pageControl];
//定时轮播图片
[self startTimer];
}
//启动定时器
-(void)startTimer
{
timer=[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
//接下来要显示的图片
-(void)nextImage
{
int page=0;
if (pageControl.currentPage==count-1) {
page =0;
pageControl.currentPage=0;
}else{
pageControl.currentPage++;
page=(int)pageControl.currentPage;
}
CGFloat offWidth=(page)*scrollViewDemo.frame.size.width;
[scrollViewDemo setContentOffset:CGPointMake(offWidth, -64)];
}
-(void)viewWillDisappear:(BOOL)animated{
[timer invalidate];
}
#pragma mark-UIScrollViewDelegate
//滑动的时候对应的修改pagecontrol
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGFloat width=scrollView.frame.size.width;
float page=(scrollView.contentOffset.x+width*0.5)/width;
if (scrollView.contentOffset.x>width*3.1) {
pageControl.currentPage=0;
[UIView setAnimationDuration:0.3];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
scrollView.contentOffset=CGPointMake(0, -64);
}
if (scrollView.contentOffset.x<-width*0.1) {
pageControl.currentPage=3;
[UIView setAnimationDuration:0.3];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
scrollView.contentOffset=CGPointMake(width*3, -64);
}
NSLog(@"scroll.x=%f",scrollView.contentOffset.x);
pageControl.currentPage=(int)page;
}
//将开始滑动的时候,定时器关闭
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
[timer invalidate];
timer=nil;
}
//滑动结束以后开始定时器
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
[self startTimer];
}
@end