工程里遇到了无缝滚动的需求,自己尝试着写了下,原理基本就是通过多建2个imageView,一个放在最前,一个放在最后,然后通过偏移量判断,[scrollView setContentOffset: animated:NO];
或者 [scrollView scrollRectToVisible: animated:NO];
再通过此方法改变位置实现,最后发现怎么都不能真正的无缝。
上网查了资料,原理虽然跟我原理一样,但处理的比我好很多,不过整理的太乱,于是想整理清楚分享给大家,本无颜称为原创,但毕竟自己原理无错,也是自己整理的,就脸厚了一下。
宏
#define WIDTH 375 //页面宽
#define HEIGHT 400 //页面高
创建ScrollView
@interface ViewController ()
{
NSMutableArray *imageArray;
}
- (void)viewDidLoad {
[super viewDidLoad];
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];
}
}