1.将图片放进images文件夹,并改名为images.bundle.拖进项目中
2拖动scrollView 并在左上角按住Scroll View 拖到View Controller中 选择deleagte.
这时候.指定Scroll View的代理为controller.
为指定的controller加上代理
#import <UIKit/UIKit.h> @interface CSZViewController : UIViewController <UIScrollViewDelegate> //ViewPager @property (weak, nonatomic) IBOutlet UIScrollView *scrollView; @end
@implementation CSZViewController - (void)viewDidLoad { [super viewDidLoad]; int width=self.view.frame.size.width; int height=self.view.frame.size.height; //从bundle压缩文件中取出多页的内容路径 NSString *bundlePath=[[NSBundle mainBundle] pathForResource:@"images" ofType:@"bundle"]; NSBundle *bundle=[[NSBundle alloc] initWithPath:bundlePath]; self.imagesArr=[bundle pathsForResourcesOfType:@"jpg" inDirectory:nil]; self.scrollView.contentSize=CGSizeMake(self.imagesArr.count*width,height); //创建分页 for (int i=0; i<self.imagesArr.count; i++) { UIImageView *itemImage=[[UIImageView alloc] init]; itemImage.image=[UIImage imageWithContentsOfFile:self.imagesArr[i]]; itemImage.frame=CGRectMake(i*width, 0, width, height); [self.scrollView addSubview:itemImage]; } //消除滑动时出现的滑块 self.scrollView.showsHorizontalScrollIndicator=NO; //使ViewPager富有弹性.分割每页 self.scrollView.pagingEnabled=YES; //创建标识 UIPageControl *ctr=[[UIPageControl alloc] init]; ctr.bounds=CGRectMake(0, 0, 150, 50); ctr.center=CGPointMake(width*0.5, height-50); ctr.currentPageIndicatorTintColor=[UIColor redColor]; ctr.pageIndicatorTintColor=[UIColor grayColor]; ctr.currentPage=1; //声明指示器的个数。如果不设置将不显示 ctr.numberOfPages=self.imagesArr.count; [ctr addTarget:self action:@selector(pageIndict:) forControlEvents:UIControlEventValueChanged]; [self.view addSubview:ctr]; //因为self.view已经绑定了一次,所以pageControl为弱引用 self.pageControl=ctr; } #pragma mark 点击指示器 跳转ViewPager - (IBAction)pageIndict:(id)sender { int curr=self.pageControl.currentPage; NSLog(@"%d",curr); self.scrollView.contentOffset=CGPointMake(self.view.frame.size.width*curr, 0) ; } #pragma mark 当滑动ViewPager时停下来 让对应的指示器进行改变 -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { int offSetX=self.scrollView.contentOffset.x; int index=offSetX/self.view.frame.size.width; self.pageControl.currentPage=index; } @end
-----------附加知识点-----------
self.scroll.backgroundColor=[UIColor grayColor];//设置背景颜色
self.scroll.contentInset=UIEdgeInsetsMake(0, 10, 0, 10);//设置边距偏移量
self.scroll.pagingEnabled=YES;//设置分页功能
self.scroll.showsHorizontalScrollIndicator=NO;//设置水平滑块