在.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(, , scrollWidth, 20)];
self.pageControl.center = CGPointMake(scrollWidth * 0.5, scrollHeight - );
self.pageControl.userInteractionEnabled = NO;
self.pageControl.numberOfPages = ;
self.pageControl.currentPage = ; //定义滚动视图
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(, , scrollWidth, scrollHeight)];
self.scrollView.contentSize = CGSizeMake( * scrollWidth, scrollHeight);
self.scrollView.pagingEnabled = YES;
self.scrollView.delegate = self; //添加7张图片
for (int i = ; i <= ; i++) {
UIImageView *imageView = [[[UIImageView alloc] initWithFrame:CGRectMake(scrollWidth * (i - ), , 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;
}
首先,先添加滚动视图后添加分页控件,并且禁止分页控件的用户交互,不然视图就不会出现滚动效果了。
在代理方法当中用偏移量除以控件宽度,可以得到页数。