UIScrollView同样是继承UIView,主要是对于其他组件内容一屏显示不完整,所以采用分屏显示。
- (void)viewDidLoad { [super viewDidLoad];
UIScrollView *scrol=[[UIScrollView alloc]init]; //可视范围 scrol.frame=self.view.bounds; _scroll=scrol; [self.view addSubview:scrol];
CGFloat scrolWidth=scrol.frame.size.width; CGFloat scrolHeight=scrol.frame.size.height;
//添加所有的imagesview // [UIImage imageNamed:@"pages.bundle/1.jpg"]; for (int i=1; i<=5; i++) { NSString *name=[NSString stringWithFormat:@"pages.bundle/%d.jpg",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-50); //设置页数 pageControl.numberOfPages=kCount; //当前选中页码 pageControl.currentPageIndicatorTintColor=[UIColor grayColor]; //其他页码 pageControl.pageIndicatorTintColor=[UIColor blackColor];
[pageControl addTarget:self action:@selector(pageChange) forControlEvents:UIControlEventValueChanged]; //添加到控制器view上 [self.view addSubview:pageControl]; _control=pageControl; //设置代理 scrol.delegate=self; //弹簧效果 scrol.bounces=NO; } -(void)pageChange{ int page=_control.currentPage; CGFloat offSetX=page*_scroll.frame.size.width; [UIView beginAnimations:nil context:nil]; _scroll.contentOffset=CGPointMake(offSetX, 0); [UIView commitAnimations];
} //滚动代理 scroll减速完毕调用 -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ //获取滚动位置 //页码 int pageNo= scrollView.contentOffset.x/scrollView.frame.size.width; _control.currentPage=pageNo; } |
总结:
1.主要属性scrol.contentSize,设置滚动范围,而scrol.frame是可视范围
2.如果要监听分页操作要控制器充当pagecontrol的代理
3.scrollViewDidEndDecelerating,scroll减速完毕调用,也就是说当用户手松开的那一刻