首页 > 代码库 > 开发进阶12_UIScrollView分页_PageControl
开发进阶12_UIScrollView分页_PageControl
/*
下面的方法提供了UIScrollView的分页功能
PageControl的一些设置等
但是只适用于少量的图片(比如软件前面的新功能介绍)
*/
#define kCount 8
@interface ViewController () <UIScrollViewDelegate>
{
UIPageControl *_pageControl;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//获取view的宽高
CGFloat w = self.view.frame.size.width;
CGFloat h = self.view.frame.size.height;
for (int i = 0; i < kCount; i++) {
UIImageView *imageView = [[UIImageView alloc] init];
//1.设置frame
imageView.frame = CGRectMake(i * w, 0, w, h);
//2.设置图片
NSString *fileName = [NSString stringWithFormat:@"0%d.jpg",i + 1];
imageView.image = [UIImage imageNamed:fileName];
[_scrollView addSubview:imageView];
}
//height == 0 代表禁止垂直方向滚动
_scrollView.contentSize = CGSizeMake(kCount * w, 0);
_scrollView.showsHorizontalScrollIndicator = NO;
//执行分页
//根据UIScrollView控件的可视范围将图片分成不同的区域
_scrollView.pagingEnabled = YES;
//设置代理
_scrollView.delegate = self;
//添加PageControl
UIPageControl *pageControl = [[UIPageControl alloc] init];
pageControl.center = CGPointMake(w * 0.5, h - 20);
pageControl.bounds = CGRectMake(0, 0, 150, 50);
//一共显示多少个圆点
pageControl.numberOfPages = kCount;
//设置非选中的圆点的颜色
pageControl.pageIndicatorTintColor = [UIColor redColor];
//设置选中的圆点的颜色
pageControl.currentPageIndicatorTintColor = [UIColor blueColor];
//禁止圆点的点击事件
pageControl.enabled = NO;
[self.view addSubview:pageControl];
_pageControl = pageControl;
}
#pragma mark - UIScrollView的代理方法
#pragma mark 当scrollView正在滚动的时候调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
int page = scrollView.contentOffset.x /scrollView.frame.size.width;
//设置页码
_pageControl.currentPage = page;
}
@end
开发进阶12_UIScrollView分页_PageControl