首先找8张jpg的图片,将它的名字分别设置为01.png......08.jpg,然后将代码运行,就可看见效果
- (void)viewDidLoad
{
[superviewDidLoad];
_scrollView = [[UIScrollViewalloc]init];
//设置scrollview的可视范围
_scrollView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
//1.创建UIImageView用来显示在UIScrollView上
CGFloat w = self.view.frame.size.width;
CGFloat h = self.view.frame.size.height;
for (int i = 0; i < 9; i++) {
NSString *imageName = [NSStringstringWithFormat:@"0%d.jpg",i+1];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageViewalloc]initWithImage:image];
//2.设置imageview的frame
imageView.frame = CGRectMake(i * w, 0, w, h);
[_scrollView addSubview:imageView];
}
//3.设置scrollview的内容尺寸
_scrollView.contentSize = CGSizeMake(w * 8, 0);
_scrollView.delegate = self;
_scrollView.pagingEnabled = YES;
[self.viewaddSubview:_scrollView];
//4.添加pagecontrol
UIPageControl *pageControl = [[UIPageControlalloc]init];
pageControl.currentPageIndicatorTintColor = [UIColorredColor];
pageControl.pageIndicatorTintColor = [UIColorblackColor];
pageControl.center = CGPointMake(160, 440);
pageControl.bounds = CGRectMake(0, 0, 80, 20);
//5.如果不设置总页数,那么就不会显示pagecontrol
pageControl.numberOfPages = 8;
//6.禁止默认的点击功能
pageControl.enabled = NO;
[self.view addSubview:pageControl];
_pageControl = pageControl;
}
#pragma mark - scrollview的代理方法,此方法在拖动scrollview时就会调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//7.设置pagecontrol的当前值,它的当前值也就是scrollview的contentoffset的x除以scrollview的宽度,
int page = _scrollView.contentOffset.x / scrollView.frame.size.width;
_pageControl.currentPage = page;
}