默认的UIScrollView滑动到底之后(假设往右),就无法继续往右滑了,但为了更好的用户体验,我们继续往右滑是自动回到第一页。这里提供一个方案。
假设有5页,其中分别放着1.jpg 2.jpg 3.jpg 4.jpg 5.jpg五张图,为支持无限滚动,我们把最后一张图复制一份追加到第一张左边,把第一张图复制一份追加到最后一张图右边,即新的UIScrollView有7页,分别是
[1号:5.jpg][2号:1.jpg][3号:2.jpg][4号:3.jpg][5号:4.jpg][6号:5.jpg][7号:1.jpg]
然后把初始的位置移动到2号。接下来,如果用户滑动到7号位置,则立刻把位置更换到2号,此时用户并没有发现位置发生了改变,从而实现了无限往右滚。同理,如果用户滑动到1号位置,则立刻把位置更换到6号,实现无限往左滚。
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 100, WIDTH, HEIGHT)];
self.scrollView.bounces = YES; //是否允许弹性滑动
self.scrollView.pagingEnabled = YES; //设置是否分页
self.scrollView.delegate = self; //代理
self.scrollView.userInteractionEnabled = YES; //交互性
添加五张图片
imageArray = [[NSMutableArray alloc] init];
[imageArray addObject:@"image1"];
[imageArray addObject:@"image2"];
[imageArray addObject:@"image3"];
[imageArray addObject:@"image4"];
[imageArray addObject:@"image5"];
添加最后一张图片到第一个位置
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[imageArray objectAtIndex:([imageArray count]-1)]]];
imageView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
[self.scrollView addSubview:imageView];
for (int i = 0;i<[imageArray count];i++) {
//loop this bit
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[imageArray objectAtIndex:i]]];
imageView.frame = CGRectMake((WIDTH * i) + 320, 0, WIDTH, HEIGHT);
[self.scrollView addSubview:imageView];
//
}
添加第一张图片到第最后一个位置
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[imageArray objectAtIndex:0]]];
imageView.frame = CGRectMake((WIDTH * ([imageArray count] + 1)), 0, WIDTH, HEIGHT);
[self.scrollView addSubview:imageView];
[self.scrollView setContentSize:CGSizeMake(WIDTH * ([imageArray count] + 2), HEIGHT)];
[self.scrollView setContentOffset:CGPointMake(0, 0)];
[self.view addSubview:self.scrollView];
[self.scrollView scrollRectToVisible:CGRectMake(WIDTH,0,WIDTH,HEIGHT) animated:NO];
代理方法中控制切换
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
CGPoint point=scrollView.contentOffset;
if ((int)point.x==0) {
[self.scrollView scrollRectToVisible:CGRectMake(WIDTH * [imageArray count],0,WIDTH,HEIGHT) animated:NO];
} else if ((int)point.x==([imageArray count]+1)*WIDTH) {
[self.scrollView scrollRectToVisible:CGRectMake(WIDTH,0,WIDTH,HEIGHT) animated:NO];
}
}
至此,实现了无限滚动。