UIKit框架-高级控件:2.UIScrollView的单图分页设置
在前面, 我们了解了UIScrollView的基本属性, 也知道了它运作之后的效果, 现在让我们来看看UIScrollView的其他更高级的功能, 那就是分页设置, 下面让我们来看看如何设置分页.
1.设置全局变量:
@interface ViewController () { UIPageControl *_pageControl; UIScrollView *_scrollView; } @end
#import <UIKit/UIKit.h> @interface ViewController : UIViewController <UIScrollViewDelegate> @end
3.添加一个UIScrollView:
#pragma mark - 添加ScrollView - (void)myScrollView { // 1.实例化ScrollView _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 28, self.view.frame.size.width, self.view.frame.size.height)]; [_scrollView setBackgroundColor:[UIColor grayColor]]; // 2.设置ScrollView内容 UIImage *image = [UIImage imageNamed:@"002.jepg"]; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; [_scrollView addSubview:imageView]; // 3.设置ScrollView属性 [_scrollView setContentSize:image.size]; [_scrollView setBounces:NO]; [_scrollView setShowsHorizontalScrollIndicator:NO]; // 4.ScrollView分页设置 [_scrollView setPagingEnabled:YES]; [self.view addSubview:_scrollView]; // 设置ScrollView为代理 [_scrollView setDelegate:self]; }
4.设置ScrollView的代理方法
#pragma mark - 设置ScrollView代理方法 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { NSInteger pageNo = scrollView.contentOffset.x / scrollView.bounds.size.width; [_pageControl setCurrentPage:pageNo]; }
5.添加pageControl
- (void)myPageControl { // 1.添加分页控件 _pageControl = [[UIPageControl alloc]init]; // 1.1指定位置和大小 [_pageControl setBounds:CGRectMake(0, 0, 150, 50)]; [_pageControl setCenter:CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height - 50)]; // 2.设置页面属性 [_pageControl setNumberOfPages:2]; [_pageControl setCurrentPage:0]; [_pageControl setCurrentPageIndicatorTintColor:[UIColor redColor]]; [_pageControl setPageIndicatorTintColor:[UIColor greenColor]]; // 3.监听分页控制器的变化 // PS: 第三个参数是ValueChanged [_pageControl addTarget:self action:@selector(updatePageChanged:) forControlEvents:UIControlEventValueChanged]; [self.view addSubview:_pageControl]; }
6.添加pageControl的监听方法
#pragma mark 分页控制器的监听方法 - (void)updatePageChanged:(UIPageControl *)pageControl { CGFloat offsetX = pageControl.currentPage * _scrollView.bounds.size.width; [_scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES]; }
7.添加所有方法到viewDidload中
- (void)viewDidLoad { [super viewDidLoad]; [self myScrollView]; [self myPageControl]; }
最后实现的效果:
好了, 这次我们就讲到这里, 下次我们继续~~