实现UIScrollView循环滚动
我们可以在scrollview里面这样添加图片的顺序, img 4, img1, img2, img3, img 4 ,img1,img 2,位置分别是 0,1,2,3,4,5,6
- (void)viewDidLoad {
[super viewDidLoad];
//创建scrollview
_scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 220)];
_scrollView.contentSize = CGSizeMake(WIDTH*7, 220);
//使整页滚动
_scrollView.pagingEnabled = YES;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.backgroundColor = [UIColor whiteColor];
//设置滚动条风格
//_scrollView.indicatorStyle = UIScrollViewIndicatorStyleBlack;
//初始位置
_scrollView.contentOffset = CGPointMake(WIDTH, 0);
NSLog(@"_scrollView.contentOffset.x/WIDTH = %f",_scrollView.contentOffset.x/WIDTH);
//关闭弹簧效果
_scrollView.bounces = NO;
_scrollView.delegate = self;
_scrollView.userInteractionEnabled = YES;
_scrollView.tag = 200;
//创建uipagecontroll
_pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(WIDTH - 100,10, 100, 1)];
//设置小点点颜色
//_pageControl.pageIndicatorTintColor = [UIColor whiteColor];
_pageControl.numberOfPages = 4;
_pageControl.userInteractionEnabled = YES;
_pageControl.tag = 10;
//添加imageView
for (int i = 0 ; i < 7 ; i++) {
if (i<5 && i >0) {
UIImageView * imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(i * WIDTH, 0, WIDTH, 220)];
imageView1.image = [UIImage imageNamed:@"image1"];//按顺序1.2.3.4张图片
imageView1.userInteractionEnabled = YES;
[_scrollView addSubview:imageView1];
}else if (i == 0)
{
UIImageView * imageView1 = [[UIImageViewalloc]initWithFrame:CGRectMake(i * WIDTH,0,WIDTH,220)];
imageView1.image = [UIImageimageNamed:@"image4"];//第4张图片
[_scrollView addSubview:imageView1];
}
else if(i == 5)
{
UIImageView * imageView1 = [[UIImageViewalloc]initWithFrame:CGRectMake(i * WIDTH,0,WIDTH,220)];
imageView1.image = [UIImageimageNamed:@"image1"];//第1张图片
[_scrollView addSubview:imageView1];
}else if (i == 6)
{
UIImageView * imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(i * WIDTH, 0, WIDTH, 220)];
imageView1.image = [UIImage imageNamed:@"image2"];//第2张图片
[_scrollView addSubview:imageView1];
}
}
//停止减速时
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
if (scrollView.tag ==200) {
UIPageControl * pc = (UIPageControl *)[self.view viewWithTag:10];
int currentPage =scrollView.contentOffset.x/WIDTH;
NSLog(@"currentPage = %d",currentPage);
if (currentPage > 5) {
_scrollView.contentOffset = CGPointMake(WIDTH * 2, 0);
} else if (currentPage<1) {
_scrollView.contentOffset = CGPointMake(4*WIDTH,0);
pc.currentPage = 4;
}
if (currentPage >0 && currentPage < 5) {
pc.currentPage = currentPage-1;
}else if (currentPage == 5)
{
pc.currentPage = 0;
}else if (currentPage == 6)
{
pc.currentPage = 1;
}else if(currentPage == 0)
{
pc.currentPage = 3;
}
NSLog(@"pc.currentPage = %ld",(long)pc.currentPage);
}
}