1.要实现图片轮播首先我们先来创建图片数组
- (NSArray *)arrayImage
{
if(!_arrayImage)
{
_arrayImage = @[@"img_05.png",@"img_01.png",@"img_02.png",@"img_03.png",@"img_04.png",@"img_05.png",@"img_01.png"];
}
return _arrayImage;
}
2.然后来创建一个scrollView
//添加滚动图
- (UIScrollView *)myScrollView
{
if(!_myScrollView)
{
_myScrollView = [[UIScrollView alloc]init];
_myScrollView.backgroundColor = [UIColor grayColor];
CGFloat screenWidth = SCREEN_SIZE.width;
_myScrollView.frame = CGRectMake(10, 69, screenWidth-20, 130);
//设置分页
_myScrollView.pagingEnabled = YES;
//隐藏滚动条
_myScrollView.showsHorizontalScrollIndicator = NO;
//设置代理(这里得到扩展里面去添加代理,才能使用scrollView的代理方法)
_myScrollView.delegate = self;
//设置弹回效果(设置弹回效果不然会有bug看到后面的背景)
_myScrollView.bounces = NO;
}
return _myScrollView;
}
3.将图片添加到scrollView里面去
- (void) addImageToScrollView
{
for(int i=0;i<self.arrayImage.count;i++)
{
UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:self.arrayImage[i]]];
imageView.frame = CGRectMake(SCROLL_SIZE.width*i, 0, SCROLL_SIZE.width, SCROLL_SIZE.height);
//添加到滚动视图
[self.myScrollView addSubview:imageView];
}
//设置总偏移量
self.myScrollView.contentSize = CGSizeMake(self.arrayImage.count*SCROLL_SIZE.width, 0);
//设置图片启动偏移量
self.myScrollView.contentOffset = CGPointMake(SCROLL_SIZE.width, 0);
}
4.添加一个pageControl来显示图片的分页
//添加pageControl
- (UIPageControl *) myPageControl
{
if(!_myPageControl)
{
_myPageControl = [[UIPageControl alloc]init];
_myPageControl.bounds = CGRectMake(0, 0, 200, 24);
//设置控件位置
_myPageControl.center = CGPointMake(SCROLL_SIZE.width/2,CGRectGetMaxY(self.myScrollView.frame)-12);
//设置偏移量
_myPageControl.numberOfPages = self.arrayImage.count-2;
//设置分页的背景颜色
_myPageControl.pageIndicatorTintColor = [UIColor whiteColor];
//设置当前页码颜色
_myPageControl.currentPageIndicatorTintColor = [UIColor grayColor];
}
return _myPageControl;
}
5.调用scrollView的代理方法设置图片页码
//滚动代理回调方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//设置图片对应的pageControll页码(减一是因为默认会增加一)
self.myPageControl.currentPage = scrollView.contentOffset.x/SCROLL_SIZE.width+0.5-1;
}
6.调用scrollView代理方法(完成滚动)设置图片循环显示
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
//设置页码
NSInteger pageNumber = scrollView.contentOffset.x/SCROLL_SIZE.width+0.5;
if(pageNumber>5)
{
//设置到把偏移量设置到第一张的位置
scrollView.contentOffset = CGPointMake(SCROLL_SIZE.width, 0);
}
if(pageNumber<1)
{
//设置偏移量到第5张图片
scrollView.contentOffset = CGPointMake(SCROLL_SIZE.width*5, 0);
}
}
注:还有一种是图片自动轮播的。这个可以增加一个NStimer来控制,然后需要注意的是:
一个是手动拖动图片的时候停止自动播放,手动拖动图片完毕的时候,继续自动播放。
另外一个是到scrollView动画完成的时候去调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
这个方法。来达到循环播放的效果