UIPageControl页控制器

一、基本知识

#import "ViewController.h"
@interface ViewController ()<UIScrollViewDelegate>{
    UIScrollView *scrollview;
    UIPageControl *page;
}

@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    page = [[UIPageControl alloc]initWithFrame:CGRectMake(20, 150, 200, 30)];
    page.backgroundColor = [UIColor yellowColor];
    page.numberOfPages = 10;//设置页数(多少个点)
    page.currentPage = 0;//设置当前选中页
    NSLog(@"%zi",page.currentPage);//获取当前选中页下标
    page.pageIndicatorTintColor = [UIColor greenColor];//未选中颜色
    page.currentPageIndicatorTintColor = [UIColor redColor];//当前选中的颜色
    [page addTarget:self action:@selector(change:) forControlEvents:UIControlEventValueChanged];
   
    [self.view addSubview:page];
   
    scrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(20, 150, 300, 400)];
    scrollview.contentSize = CGSizeMake(900, 0);
    scrollview.delegate = self;
    scrollview.pagingEnabled = YES;
    [self.view addSubview:scrollview];
   
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 300, 400)];
    view.backgroundColor = [UIColor grayColor];
    [self.view addSubview:view];
   
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(300, 0, 300, 400)];
    view1.backgroundColor = [UIColor blackColor];
    [self.view addSubview:view1];
   
    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(600, 0, 300, 400)];
    view2.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:view2];
   
}

-(void)change:(id)pc{
    NSLog(@"%zi",[pc currentPage]);//获取页数
    CGPoint p = {[pc currentPage]*300,0};//
    [scrollview setContentOffset:p animated:YES];//允许动画
   
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    int index =  scrollview.contentOffset.x/scrollview.frame.size.width;
    page.currentPage = index;
}
原文地址:https://www.cnblogs.com/wxzboke/p/4978409.html