iOS之简单图片轮播器(分页视图)

#import "ViewController.h"

@interface ViewController ()<UIScrollViewDelegate>

@property (strong, nonatomic) UIScrollView *scrollView;

@property (strong, nonatomic) UIPageControl *pageControl;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:self.scrollView];
    [self.view addSubview:self.pageControl];

    [self loadImageViewToScrollView];
}

#pragma mark - 方法调用
//加载图片到滚动视图上
- (void)loadImageViewToScrollView
{
        
    for (int i = 0; i < 5; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.frame = CGRectMake(i*self.scrollView.bounds.size.width, 0, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height);
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",i+1]];
        imageView.image = image;
        [self.scrollView addSubview:imageView];
    }
}

//监听滚动事件
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //根据滚动的偏移量计算当前页页数
    int page =  (int)(scrollView.contentOffset.x/scrollView.frame.size.width+0.5);
    self.pageControl.currentPage = page;
}



#pragma mark - 懒加载
- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(20, 50, self.view.frame.size.width-40, 300)];
        _scrollView.backgroundColor = [UIColor redColor];
        _scrollView.delegate = self;
        _scrollView.contentSize = CGSizeMake(self.scrollView.bounds.size.width * 4, 0);
        _scrollView.showsHorizontalScrollIndicator = NO; //取消横向滚动条
        _scrollView.pagingEnabled = YES; //开启分页功能
    }
    return _scrollView;
}


- (UIPageControl *)pageControl
{
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(self.view.frame.size.width-100, 130, 50, 30)];
        _pageControl.numberOfPages = 4;
        _pageControl.pageIndicatorTintColor = [UIColor greenColor]; //其他页指示器颜色
        _pageControl.currentPageIndicatorTintColor = [UIColor orangeColor]; //当前页指示器颜色
    }
    return _pageControl;
}

@end

PS:先简单的图片轮播器代码实现,后续会对这个整体进行封装

你可能感兴趣的:(iOS之简单图片轮播器(分页视图))