一、多图分页代码
#import "ViewController.h"
@interface ViewController ()
@property(weak,nonatomic)UIScrollView * scrollView;
@property (weak, nonatomic) UIPageControl *pageControl;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIScrollView *scroll = [[UIScrollView alloc]initWithFrame:self.view.bounds];
[self.view addSubview:scroll];
self.scrollView = scroll;
NSMutableArray *imageArray = [[NSMutableArray alloc]initWithCapacity:5];
for (NSInteger i=1; i<=5; i++) {
NSString *imageName = [NSString stringWithFormat:@"%ld.jpg",i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[imageArray addObject:imageView];
}
CGFloat width = scroll.bounds.size.width;
[imageArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
UIImageView * imageView = obj;
[imageView setFrame:CGRectMake(idx*width, 0, width, scroll.bounds.size.height)];
[scroll addSubview:imageView];
}];
[scroll setPagingEnabled:YES];
[scroll setBounces:NO];
[scroll setShowsHorizontalScrollIndicator:NO];
[scroll setContentSize:CGSizeMake(scroll.bounds.size.width*imageArray.count, scroll.bounds.size.height)];
[scroll setDelegate:self];
UIPageControl * pageControl = [[UIPageControl alloc]init];
CGSize size = [pageControl sizeForNumberOfPages:imageArray.count];
[pageControl setFrame:CGRectMake(0, 0, size.width, size.height)];
[pageControl setCenter:CGPointMake(width/2, 600)];
[pageControl setNumberOfPages:imageArray.count];
[pageControl setCurrentPage:0];
[pageControl setCurrentPageIndicatorTintColor:[UIColor redColor]];
[pageControl setPageIndicatorTintColor:[UIColor blueColor]];
[pageControl addTarget:self action:@selector(pageChanged:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:pageControl];
self.pageControl = pageControl;
}
#pragma mark - 分页控件页码变化监听方法
-(void)pageChanged:(UIPageControl*)sender {
NSLog(@"分页了----%ld", sender.currentPage);
CGFloat offsetX = sender.currentPage*self.scrollView.bounds.size.width;
[self.scrollView setContentOffset:CGPointMake(offsetX, 0)];
}
#pragma mark - UIScrollView代理方法
#pragma mark 滚动视图减速事件
-(void)scrollViewDidEndDecelerating:(nonnull UIScrollView *)scrollView{
NSLog(@"页面停止滚动");
NSInteger pageNo = scrollView.contentOffset.x / scrollView.bounds.size.width;
[self.pageControl setCurrentPage:pageNo];
}
@end
二、图示