/** 整个背景滚动视图*/
@property (nonatomic,strong) UIScrollView *scrol;
/** 添加pagecontrol*/
@property (nonatomic,strong) UIPageControl *pageControl;
- (void)viewDidLoad
{
[super viewDidLoad];
UIScrollView *scrol = [[UIScrollView alloc]init];
//可视范围
scrol.frame = self.view.bounds;
self.scrol = scrol;
[self.view addSubview:scrol];
CGFloat scrolWidth=scrol.frame.size.width;
CGFloat scrolHeight=scrol.frame.size.height;
//添加所有的imagesview
// [UIImage imageNamed:@"pages.bundle/1.jpg"];
NSInteger kCount = 4;
for (int i = 1; i <= kCount; i++) {
NSString *name = [NSString stringWithFormat:@"UploadFile%d",i];
UIImage *image = [UIImage imageNamed:name];
UIImageView *imageView=[[UIImageView alloc]init];
imageView.image=image;
CGFloat x = (i-1)*scrol.frame.size.width;
imageView.frame = CGRectMake(x,0, scrolWidth, scrolHeight);
[scrol addSubview:imageView];
}
//设置滚动范围
scrol.contentSize=CGSizeMake(kCount * scrolWidth, 0);
//隐藏水平滚动条
scrol.showsHorizontalScrollIndicator=NO;
//设置分页
scrol.pagingEnabled=YES;
//添加pagecontrol
UIPageControl *pageControl=[[UIPageControl alloc]init];
pageControl.bounds=CGRectMake(0, 0, 150, 50);
pageControl.center=CGPointMake(scrolWidth*0.5, scrolHeight - 100);
//设置页数
pageControl.numberOfPages = kCount;
//当前选中页码
pageControl.currentPageIndicatorTintColor=[UIColor grayColor];
//其他页码
pageControl.pageIndicatorTintColor=[UIColor blackColor];
[pageControl addTarget:self action:@selector(pageChange) forControlEvents:UIControlEventValueChanged];
//添加到控制器view上
[self.view addSubview:pageControl];
self.pageControl = pageControl;
//设置代理
scrol.delegate=self;
//弹簧效果
scrol.bounces=NO;
}
pragma mark -- Action
-(void)pageChange{
int page = (int)self.pageControl.currentPage;
CGFloat offSetX= page *self.pageControl.frame.size.width;
[UIView beginAnimations:nil context:nil];
self.scrol.contentOffset = CGPointMake(offSetX, 0);
[UIView commitAnimations];
}
pragma mark -- UIScrollViewDelegate
//滚动代理 scroll减速完毕调用
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//获取滚动位置
//页码
int pageNo= scrollView.contentOffset.x/scrollView.frame.size.width;
self.pageControl.currentPage=pageNo;
}
总结:
1.主要属性scrol.contentSize,设置滚动范围,而scrol.frame是可视范围
2.如果要监听分页操作要控制器充当pagecontrol的代理
3.scrollViewDidEndDecelerating,scroll减速完毕调用,也就是说当用户手松开的那一刻