滚动视图
效果图要求:页数与当前页面相同,当翻到最后一页继续往下翻会回到第一页,当翻到第一页继续往上翻会回到最后一页。
想法:在第一页前添加一个和最后一页相同的视图,再通过代理方法控制。
1.创建滚动视图
self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
self.scrollView.backgroundColor = [UIColor blueColor];
self.scrollView.contentSize = CGSizeMake(kWidth * 8, 0);// 设置内部滚动容量
self.scrollView.contentOffset = CGPointMake(kWidth, 0);// 设置偏移量
self.scrollView.pagingEnabled = YES;// 设置是否整页翻页
self.scrollView.showsHorizontalScrollIndicator = NO;// 设置横向指示条是否显示
self.scrollView.delegate = self;
[self.view addSubview:self.scrollView];
2.创建第一张图片
UIImageView *firstImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"h7.jpeg" ofType:nil];
firstImageView.image = [UIImage imageWithContentsOfFile:imagePath];
[self.scrollView addSubview:firstImageView];
3.循环创建内部图片
for (int i = 1; i < 8; i++) {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * kWidth, 0, kWidth, kHeight)];
imagePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"h%d.jpeg", i] ofType:nil];
imageView.image = [UIImage imageWithContentsOfFile:imagePath];
[self.scrollView addSubview:imageView];
}
4.创建页面指示器
self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(100, kHeight - 50, kWidth - 100 * 2, 50)];
self.pageControl.numberOfPages = 7;
self.pageControl.currentPage = 0;
self.pageControl.currentPageIndicatorTintColor = [UIColor redColor];
self.pageControl.pageIndicatorTintColor = [UIColor whiteColor];
[self.pageControl addTarget:self action:@selector(pageChange) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:self.pageControl];
5.页面指示器方法
- (void)pageChange {
int page = (int)self.pageControl.currentPage + 1;
CGPoint offset = CGPointMake(page * kWidth, 0);
[self.scrollView setContentOffset:offset animated:YES];
}
6.添加UIScrollViewDelegate协议并且重写协议方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
// 获取偏移量
int offsetx = scrollView.contentOffset.x;
// 根据偏移量排除第一页
if (offsetx < 0) {
[scrollView setContentOffset:CGPointMake(7 * kWidth, 0) animated:NO];
}
if (offsetx > 7 * kWidth) {
[scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
}
// 根据偏移量设置页数指示器
int page = offsetx / kWidth - 1;
self.pageControl.currentPage = page >= 0 ? page : 7;
}
完成
网友评论