【iOS】滚动视图(UIScrollview)点视图(UIPageControl)

滚动视图 UIScrollview

UIScrollView * scrollView = [[UIScrollView alloc]init];

scrollView.frame = CGRectMake(0, 30, 320, 200);
    
scrollView.backgroundColor = [UIColor redColor];

//设置内容的大小 
scrollView.contentSize = CGSizeMake(320 * 7, 200);

//是否具有分页能力
scrollView.pagingEnabled = YES;

//是否显示水平方向的指示条
scrollView.showsHorizontalScrollIndicator = NO;

//是否显示竖直方向的指示条
scrollView.showsVerticalScrollIndicator = NO;
    
//禁止scrollView的位置自动调整
self.automaticallyAdjustsScrollViewInsets = NO;

//scrollView上可以添加任意类型的子视图,不一定都是图像视图
for (int i = 1 ; i < 8; i++)
{
    UIImageView * imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(320 * (i-1), 0,320, 200)];
    NSString * imageName = [NSString stringWithFormat:@"%d.jpg",i];
    imageView1.image = [UIImage imageNamed:imageName];
    [scrollView addSubview:imageView1];
}

[self.window addSubview:scrollView];

页面控制的视图(UIPageControl):

/* 父类是UIControl */

UIPageControl  * pageControl =  [[UIPageControl alloc]init];

pageControl.frame = CGRectMake(100, 100, 200, 40);

pageControl.backgroundColor = [UIColor yellowColor];

//设置页面数目
pageControl.numberOfPages = 6;

//设置当前页(页号从0开始)
pageControl.currentPage = 1;

//设置当前页的颜色
pageControl.currentPageIndicatorTintColor = [UIColor blackColor];

//设置其他页的颜色
pageControl.pageIndicatorTintColor = [UIColor redColor];

//当currentPage发生变化的时候,会调用changePage方法;
[pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
    
[self.window addSubview:pageControl];

-(void)changePage:(UIPageControl*)pageControl 
{
    NSLog(@"---");
}

滚动视图和页面控制视图的联合使用

1、创建一个scrollView

2、创建一个pageControl

3、联合使用,图像视图切换时,让pageControl的currentPage做出对应的变化

//1. 设置代理
_scrollView.delegate = self;

//2. 当pageControl的currentPage发生变化的时候,让scrollView上的图像视图 做出对应的变化;
[_pageControl addTarget:self action:@selector(changePage) forControlEvents:UIControlEventValueChanged];

//3. 
-(void)changePage
{
    //获取当前是第几页
    int  page = _pageControl.currentPage ;
    
    //修改scrollView的偏移量
    _scrollView.contentOffset = CGPointMake(320 * page, 0);
}

//4.

//scrollView 滑动的过程中,会调用的协议方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView

//将要开始拖拽
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

//结束拖拽,将要减速
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate

//将要开始减速
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView

//已经结束减速;scrollView停止滑动;
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //scrollView停止滑动的时候,修改pageControl的currentPage;
    
    //根据scrollView的水平方法的偏移量计算出来当前是第几页;
   
    int page = _scrollView.contentOffset.x / 320 ;
    
    _pageControl.currentPage = page;
}

你可能感兴趣的:(【iOS】滚动视图(UIScrollview)点视图(UIPageControl))