IOS开发实战:UIPageControl分页控制器

一,创建UIPageControl分页控制器项目

UIPageControl:分页控制器,用于页码管理的UI控件,如新手引导页,广告轮播页等

1,打开Xcode,创建名为UIPageControl的工程
如何创建工程:Xcode创建HelloWorld项目

2,在ViewController.m的viewDidLoad方法中添加如下代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    // 当前视图背景设置为黑色
    self.view.backgroundColor = [UIColor blackColor];
    // 初始化UIPageControl控件,设置再页面上的位置
    UIPageControl * page = [[UIPageControl alloc]initWithFrame:CGRectMake(20, 100, 280, 30)];
    // 设置页码数量
    page.numberOfPages = 8;
    // 设置高亮页码颜色
    page.currentPageIndicatorTintColor = [UIColor redColor];
    // 添加事件
    [page addTarget:self action:@selector(changeNum:) forControlEvents:UIControlEventValueChanged];
    // 控件添加到当前视图
    [self.view addSubview:page];
}

-(void)changeNum:(UIPageControl *)page{
    NSLog(@"%lu", (long)page.currentPage);
}

3,运行代码:

IOS开发实战:UIPageControl分页控制器_第1张图片

效果如下:
    点击UIPageControl控件左侧,页码向左移动
    点击UIPageControl控件右侧,页码向右移动
    页码移动同时触发交互事件,打印Log

Log如下:
    2018-05-14 14:56:58.037 UIPageControl[1412:579008] 1
    2018-05-14 14:56:58.982 UIPageControl[1412:579008] 2
    2018-05-14 14:57:00.107 UIPageControl[1412:579008] 3
    2018-05-14 14:57:00.669 UIPageControl[1412:579008] 4
    2018-05-14 14:57:01.772 UIPageControl[1412:579008] 5
    2018-05-14 14:57:07.296 UIPageControl[1412:579008] 6
    2018-05-14 14:57:08.567 UIPageControl[1412:579008] 7
    2018-05-14 14:57:11.233 UIPageControl[1412:579008] 6
    2018-05-14 14:57:12.887 UIPageControl[1412:579008] 5
    2018-05-14 14:57:13.708 UIPageControl[1412:579008] 4
    2018-05-14 14:57:14.507 UIPageControl[1412:579008] 3
    2018-05-14 14:57:16.217 UIPageControl[1412:579008] 2
    2018-05-14 14:57:17.162 UIPageControl[1412:579008] 1
    2018-05-14 14:57:17.826 UIPageControl[1412:579008] 0
    2018-05-14 14:57:18.332 UIPageControl[1412:579008] 1
    2018-05-14 14:57:18.850 UIPageControl[1412:579008] 2
    2018-05-14 14:57:19.288 UIPageControl[1412:579008] 3
    2018-05-14 14:57:19.952 UIPageControl[1412:579008] 4
    .....

本例共有8个页码,程序初始化默认选中第0个页码(从0开始)

你可能感兴趣的:(IOS)