在.h文件当中实现UIScrollViewDelegate协议,让控制器充当代理:
#import <UIKit/UIKit.h> @interface RPRootViewController : UIViewController <UIScrollViewDelegate> @property (retain, nonatomic) UIScrollView *scrollView; @property (retain, nonatomic) UIPageControl *pageControl; @end
实现文件如下:
#import "RPRootViewController.h" @interface RPRootViewController () @end @implementation RPRootViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; CGFloat scrollWidth = [[UIScreen mainScreen] bounds].size.width; CGFloat scrollHeight = [[UIScreen mainScreen] bounds].size.height; //定义分页控件 self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 0, scrollWidth, 20)]; self.pageControl.center = CGPointMake(scrollWidth * 0.5, scrollHeight - 80); self.pageControl.userInteractionEnabled = NO; self.pageControl.numberOfPages = 7; self.pageControl.currentPage = 0; //定义滚动视图 self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, scrollWidth, scrollHeight)]; self.scrollView.contentSize = CGSizeMake(7 * scrollWidth, scrollHeight); self.scrollView.pagingEnabled = YES; self.scrollView.delegate = self; //添加7张图片 for (int i = 1; i <= 7 ; i++) { UIImageView *imageView = [[[UIImageView alloc] initWithFrame:CGRectMake(scrollWidth * (i - 1), 0, scrollWidth, scrollHeight)] autorelease]; imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"img%d.png", i]]; [self.scrollView addSubview:imageView]; } [self.view addSubview:self.scrollView]; [self.view addSubview:self.pageControl]; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { int pageNo = self.scrollView.contentOffset.x / self.scrollView.frame.size.width; self.pageControl.currentPage = pageNo; }
首先,先添加滚动视图后添加分页控件,并且禁止分页控件的用户交互,不然视图就不会出现滚动效果了。
在代理方法当中用偏移量除以控件宽度,可以得到页数。