UIScrollView -2(UIScrollView 与 UIPageControl的使用): 分页查看图片

时间:2022-06-25 22:12:44

1.初始化UIScrollView

2.设置初始化出来的UIScrollView的contentSize:

myscrollview.contentSize =CGSizeMake(CGRectGetWidth(self.view.frame)*3, 2);因为我这里有3张图片,所以要它的宽乘以3;

设置滚动视图的分页效果

myscrollview.pagingEnabled =YES;

设置滚动条的样式

myscrollview.indicatorStyle = UIScrollViewIndicatorStyleBlack;

还可以通过 contentOffset 来判断 滚动到第几屏

myscrollview.contentOffset =CGPointMake(CGRectGetWidth(self.view.frame), 0);(运行之后默认在第几屏)

设置是否有反弹效果(默认值是yes 允许看到底图 并有反弹效果):

myscrollview.bounces = NO;

隐藏横向滚动条:

myscrollview.showsHorizontalScrollIndicator =NO;

挂上代理(首先肯定要声明代理):

myscrollview.delegate =self;

添加滚动视图到视图上:

[self.view addSubview:myscrollview];

添加图片

for (int i =0; i<3; i++) {

UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.view.frame)*i, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))];

img.image =[UIImage imageNamed:imgs[i]];

[myscrollview addSubview:img];

}//imgs为全局变量UIimageView;

初始化UIPageControl  UIPageControl *pagecontrol =[[UIPageControl alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.frame)-40, CGRectGetWidth(self.view.frame),40 )];

/设置pagecontrol 的总共多少个页面

pagecontrol.numberOfPages = imgs.count;

//    设置指示的当前页面(默认从0开始)

pagecontrol.currentPage = 1;

//当只有一个页面的时候隐藏pagecontrol

//    pagecontrol.hidesForSinglePage =YES;

//    设置其它小圆点的颜色

pagecontrol.pageIndicatorTintColor =[UIColor orangeColor];

//    设置当前的小圆点的颜色

pagecontrol.currentPageIndicatorTintColor = [UIColor redColor];

pagecontrol.tag =119;

[self.view addSubview:pagecontrol];

滚动结束时候会调用的方法:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

滚动视图的偏移量:

CGFloat x =scrollView.contentOffset.x;

屏幕的宽:

CGFloat w =CGRectGetWidth(self.view.frame);

偏移量除以宽得到当前页面的页数:

NSInteger curpage =x/w;

UIPageControl *page =(UIPageControl *)[self.view viewWithTag:119];

page.currentPage =curpage;

}