UIScrollView其实构建的就像一列很长的火车,每滑动一个屏幕,展示一节车厢。
//主屏幕高度
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
//主屏幕宽度
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
CGFloat kImgCount = 10; CGFloat scrollY = 20; //scrollView距离屏幕顶部的距离
CGFloat pageCtrlWidth = 200; @property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIPageControl *pageCtrl; //构建UIScrollView代码
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, scrollY, kScreenWidth, kScreenHeight - scrollY)];
self.scrollView.delegate = self;
for (int i = 0; i<kImgCount; i++) {
UIImageView *imgview = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth * i, scrollY, kScreenWidth, kScreenHeight - scrollY)];
imgview.image = [UIImage imageNamed:[NSString stringWithFormat:@"news%04d",i]];
[self.scrollView addSubview:imgview];
}
self.scrollView.contentSize = CGSizeMake(kScreenWidth * kImgCount, kScreenHeight - scrollY);//设置这一列火车的总长度
self.scrollView.pagingEnabled = YES;//分页显示
[self.view addSubview:self.scrollView]; //构建UIPageControl代码
self.pageCtrl = [[UIPageControl alloc] initWithFrame:CGRectMake((kScreenWidth - pageCtrlWidth)/2, kScreenHeight - scrollY, pageCtrlWidth, scrollY)];
self.pageCtrl.numberOfPages = kImgCount;
self.pageCtrl.pageIndicatorTintColor = [UIColor greenColor];
self.pageCtrl.currentPageIndicatorTintColor = [UIColor yellowColor];
[self.view insertSubview:self.pageCtrl aboveSubview:self.scrollView];
UIScrollView常用代理方法
//当视图滑动时
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{ }
// 当视图将要拖动的时候
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ }
//当视图停止拖拽的时候调用
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{ }