UIScrollView和UIPageControl分页浏览图片

基础篇


#import"ViewController.h"

@interfaceViewController()

//记录UIScrollView滚动的位置

@property(nonatomic,assign)CGPointcontentOffset;

//内容尺寸

@property(nonatomic,assign)CGSizecontentSize;

//上下左右边缘

@property(nonatomic,assign)UIEdgeInsetscontentInset;

//代理对象

@property(nonatomic,weak)id delegate;

//是否有弹簧效果

@property(nonatomic,assign)BOOLbounces;

//是否显示水平滚动条

@property(nonatomic,assign)BOOLshowHorizontalScrollIndictor;

//是否显示垂直滚动条

@property(nonatomic,assign)BOOLshowVerticalScrollIndictor;

@property(nonatomic,strong)UIScrollView*scrollView;

@property(nonatomic,strong)UIPageControl*pageControl;

@end

@implementationViewController

- (void)viewDidLoad {

[superviewDidLoad];

[selfsetupScrollView];

}

- (void)setupScrollView {

CGFloatw =self.view.frame.size.width;

CGFloath =self.view.frame.size.height;

UIScrollView*scrollView = [[UIScrollViewalloc]initWithFrame:self.view.frame];

//添加图片

for(inti =0; i <4; i ++) {

UIImageView*imageView = [[UIImageViewalloc]init];

imageView.contentMode=UIViewContentModeScaleAspectFit;

imageView.frame=CGRectMake(i * w,0, w, h);

NSString*imageName = [NSStringstringWithFormat:@"%d.png", i +1];

imageView.image= [UIImageimageNamed:imageName];

[scrollViewaddSubview:imageView];

}

scrollView.contentSize=CGSizeMake(w *4, h);

scrollView.showsHorizontalScrollIndicator=NO;

scrollView.pagingEnabled=YES;

scrollView.delegate=self;

[self.viewaddSubview:scrollView];

UIPageControl*pageControl = [[UIPageControlalloc]init];

pageControl.center=CGPointMake(w /2, h -20);

pageControl.bounds=CGRectMake(0,0,150,15);

pageControl.numberOfPages=4;

//非选中圆点颜色

pageControl.pageIndicatorTintColor= [UIColoryellowColor];

pageControl.currentPageIndicatorTintColor= [UIColorredColor];

pageControl.enabled=NO;

[self.viewaddSubview:pageControl];

self.pageControl= pageControl;

self.scrollView= scrollView;

}

- (void)scrollViewDidScroll:(UIScrollView*)scrollView {

intpage = scrollView.contentOffset.x/self.view.frame.size.width;

NSLog(@"%d", page);

self.pageControl.currentPage= page;

}

你可能感兴趣的:(UIScrollView和UIPageControl分页浏览图片)