标签:
//当一个对象从xib中创建初始化完毕的时候就会调用一次 -(void)awakeFromNib{ CGFloat imageH=self.scrollView.frame.size.height; CGFloat imageW=self.scrollView.frame.size.width; CGFloat imageY=0; for (int i=0; i<imageCount; i++) { UIImageView *imageView=[[UIImageView alloc]init]; CGFloat imageX=i*imageW; NSString *name=[NSString stringWithFormat:@"ad_0%i",i]; imageView.image=[UIImage imageNamed:name]; imageView.frame=CGRectMake(imageX, imageY, imageW, imageH); [self.scrollView addSubview:imageView]; } CGFloat contentSize=imageW*imageCount; self.scrollView.contentSize=CGSizeMake(contentSize, 0); self.scrollView.pagingEnabled=YES; self.pageControl.numberOfPages=imageCount; self.scrollView.showsHorizontalScrollIndicator=NO; [self addTimer]; } #pragma mark 添加定时器 -(void)addTimer{ self.timer=[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; } #pragma mark 移除定时器 -(void)removeTimer{ [self.timer invalidate]; self.timer=nil; } #pragma mark 下一个图片 -(void)nextImage{ //增加pageControl的页码 int page=0; if (self.pageControl.currentPage==imageCount-1) { page=0; }else{ page=self.pageControl.currentPage+1; } //计算imagescrollView滚动的位置 CGFloat offsetX=page*self.imagescrollView.frame.size.width; CGPoint offset=CGPointMake(offsetX, 0); [self.imagescrollView setContentOffset:offset animated:YES]; } #pragma mark 代理方法(代理方法非常重要,这个方法关联着pageControl) -(void)scrollViewDidScroll:(UIScrollView *)imagescrollView{ //根据imagescrollView滚动的位置决定pageControl显示第几页 CGFloat scrollW=imagescrollView.frame.size.width; int page=(imagescrollView.contentOffset.x+scrollW*0.5)/scrollW; self.pageControl.currentPage=page; } -(void)scrollViewWillBeginDragging:(UIScrollView *)imagescrollView{ //停止定时器 [self removeTimer]; } -(void)scrollViewDidEndDragging:(UIScrollView *)imagescrollView willDecelerate:(BOOL)decelerate{ //开启定时器 [self addTimer]; }
标签:
原文地址:http://www.cnblogs.com/hqzxbb/p/4480058.html