#import "ViewController.h"
@interface ViewController ()<UIScrollViewDelegate>{
UIScrollView *_scrollView;
UIPageControl *pageControl;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//1.创建ScrollView对象
_scrollView = [[UIScrollView alloc]
initWithFrame:CGRectMake(0,0,self.view.frame.size.width,400)];
//3.添加内容
CGFloat Y = 0;
CGFloat W = _scrollView.frame.size.width;
CGFloat H = _scrollView.frame.size.height;
UIImage *image1 = [UIImage imageNamed:[NSString stringWithFormat:@"46_7.jpg"]] ;
UIImageView *imageview1 =[[UIImageView alloc]
initWithFrame:CGRectMake(0, 0, W,H )];
imageview1.image = image1;
[_scrollView addSubview:imageview1];
for(int i=1;i<8;i++){
CGFloat X = i * W;
UIImage *image = [UIImage imageNamed:
[NSString stringWithFormat:@"46_%d.jpg",i] ];
UIImageView *imageView = [[UIImageView alloc]
initWithFrame:CGRectMake(X,Y,W,H )];
imageView.image = image;
//显示在内容视图上
[_scrollView addSubview:imageView];
}
UIImage *image2 = [UIImage imageNamed:[NSString stringWithFormat:@"46_1.jpg"]] ;
UIImageView *imageview2 =[[UIImageView alloc]
initWithFrame:CGRectMake(8*W, 0, W,H )];
imageview2.image = image2;
[_scrollView addSubview:imageview2];
//4.添加到界面上;
[self.view addSubview:_scrollView];
//5.设置内容
_scrollView.contentSize = CGSizeMake(9*W, H);
//6.设置代理
_scrollView.delegate = self;
_scrollView.pagingEnabled = YES;
_scrollView.contentOffset = CGPointMake(W, 0);
//=======================pageControl===================
CGFloat PX = 0 ;
CGFloat PH = 20;
CGFloat PY = _scrollView.frame.size.height - PH;
CGFloat PW = _scrollView.frame.size.width;
//1.创建pagecontrol对象
pageControl = [[UIPageControl alloc]
initWithFrame:CGRectMake(PX,PY,PW, PH)];
//2.显示在界面上
[self.view addSubview:pageControl];
//3.设置背景颜色
pageControl.backgroundColor = [UIColor cyanColor];
//4.设置分页数
pageControl.numberOfPages = 7;
//5.设置当前分页
pageControl.currentPage = 0;
//6.没有选中分页的填充颜色
pageControl.pageIndicatorTintColor = [UIColor redColor];
//7.选中的分页的填充颜色
pageControl.currentPageIndicatorTintColor = [UIColor purpleColor];
//8.关闭用户交互
pageControl.userInteractionEnabled = NO;
}
#pragma mark - 停止滚动协议方法
//这个方法可以实现无限轮播
- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
int page =(int) scrollView.contentOffset.x / scrollView
.frame.size.width - 1;
NSLog(@"page = %d",page);
pageControl.currentPage = page;
if (page > 6) {
[_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width, 0)];
pageControl.currentPage = 0;
}
if (page < 0) {
[_scrollView setContentOffset:CGPointMake(7*_scrollView.frame.size.width,0)];
pageControl.currentPage = 6;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end