// 创建一个scrollView
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
[self.view addSubview:scrollView];
[scrollView release];
// 设置让scrollView滚动
// 滚动范围
scrollView.contentSize = CGSizeMake(WIDTH * 9, HEIGHT);
// 按页滚动
scrollView.pagingEnabled = YES;
// 将图片添加到scrollView中
for (NSInteger i = 0; i < 7; i++) {
NSString *imgName = [NSString stringWithFormat:@"angry_%02ld.jpg", i];
// 通过图片名创建UIImageView
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imgName]];
imageView.frame = CGRectMake(WIDTH * (i + 1), 0, WIDTH, HEIGHT);
[scrollView addSubview:imageView];
[imageView release];
}
// 为使循环过渡更平滑,在前后各添加一个imageView
UIImageView *firstImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"angry_07.jpg"]];
firstImageView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
[scrollView addSubview:firstImageView];
[firstImageView release];
UIImageView *lastImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"angry_00.jpg"]];
lastImageView.frame = CGRectMake(WIDTH * 8, 0, WIDTH, HEIGHT);
[scrollView addSubview:lastImageView];
[lastImageView release];
// 偏移量(起始是第几页)
scrollView.contentOffset = CGPointMake(WIDTH * 1, 0);
// 关闭边界回弹效果
scrollView.bounces = NO;
// 关闭滚动条(水平和垂直滚动条会作为两个子视图天极道scrollView的子视图中, 如果关闭, 则不会添加)
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
// 设置代理人
scrollView.delegate = self;
scrollView.tag = 100;
// 实现循环滚动
// 减速停止时触发协议
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
if (scrollView.contentOffset.x == WIDTH * 8) {
scrollView.contentOffset = CGPointMake(WIDTH, 0);
}
if (scrollView.contentOffset.x == 0) {
scrollView.contentOffset = CGPointMake(WIDTH * 7, 0);
}
}