IOS 学习笔记,scrollView添加分页

本文介绍了一个简单的iOS应用中实现滑动分页视图的方法。通过使用UIScrollView和UIPageControl,可以轻松创建带有分页指示器的水平滑动内容。文中详细展示了如何设置UIScrollView的代理、调整其属性以便支持分页,并且通过UIPageControl来显示当前页面。此外,还介绍了如何为UIScrollView添加子视图并改变背景颜色。
 1 #import "ViewController.h"
 2  
 3 #define Width self.view.frame.size.width
 4 #define Height self.view.frame.size.height
 5 #define viewH 200
 6 @interface ViewController ()<UIScrollViewDelegate>
 7 
 8 
 9 @property(nonatomic,retain) UIScrollView * scrollView;
10 @property(nonatomic,retain) UIPageControl * pageControl;
11 
12 @end
13 
14 @implementation ViewController
15 
16 
17 
18 #pragma mark - View lifecycle
19 
20 
21 - (void)viewDidLoad
22 {
23  
24     [super viewDidLoad];
25     // Do any additional setup after loading the view, typically from a nib.
26     
27     self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, Height-viewH, Width, viewH)];
28     self.scrollView.delegate = self;
29     [self.scrollView setContentSize:CGSizeMake(Width*4, viewH)];
30     //self.scrollView.showsHorizontalScrollIndicator = YES;
31     self.scrollView.showsVerticalScrollIndicator = YES;
32     self.scrollView.pagingEnabled = YES;
33     [self.scrollView setBackgroundColor:[UIColor redColor]];
34     
35     NSArray*arr =[[NSArray alloc]initWithObjects:[UIColor grayColor],[UIColor greenColor],[UIColor blueColor],[UIColor yellowColor], nil];
36     for (int i=0; i<4; i++) {
37         UIView * view1 = [[UIView alloc]initWithFrame:CGRectMake(Width*i, 0, Width, viewH)];
38         [view1 setBackgroundColor:arr[i]];
39         [self.scrollView addSubview:view1];
40 
41     }
42     [self.view addSubview:self.scrollView];
43     
44     
45     self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 0, 200, 20)];
46     self.pageControl.center = CGPointMake(Width/2, Height-20);
47   
48     self.pageControl.numberOfPages = 4;
49     [self.pageControl addTarget:self action:@selector(pageChanged:) forControlEvents:UIControlEventValueChanged];
50     
51     [self.view addSubview:self.pageControl];
52 }
53 -(void)pageChanged:(UIPageControl*)page
54 {
55     int p = (int)page.currentPage;
56     [self.scrollView scrollRectToVisible:CGRectMake(Width*p, 0, Width, viewH) animated:YES];
57 }
58 
59 -(void)scrollViewDidScroll:(UIScrollView*)scrollView
60 {
61     CGFloat pageWith = scrollView.frame.size.width;
62     int page = floor((scrollView.contentOffset.x - pageWith/2)/pageWith)+1;
63     self.pageControl.currentPage = page;
64 }
65 
66 
67 
68 
69 
70 - (void)didReceiveMemoryWarning {
71     [super didReceiveMemoryWarning];
72     // Dispose of any resources that can be recreated.
73 }
74 
75 @end

 

转载于:https://www.cnblogs.com/mojiewei/p/5039491.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值