直接上代码,有注释
//
// ViewController.m
// SlipPicture
//
// Created by chenqianfeng on 15/12/7.
// Copyright © 2015年 chenqianfeng. All rights reserved.
//
#import "ViewController.h"
@interface ViewController (){
UIScrollView *_sView;
UIPageControl *_pgControler;
NSArray *_imageArr;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//创建数据
[self createImageArr];
//创建ScrollView
[self creatScrollView];
//创建Pagecontroller
[self createPagecontroller];
}
- (void)createImageArr
{
_imageArr = [[NSArray alloc]initWithObjects:@"3",@"0",@"1",@"2",@"3",@"0", nil];
}
- (void)creatScrollView
{
_sView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 100,[UIScreen mainScreen].bounds.size.width, 400)];
//必须设置contentSize,要不然滚动不了(scrollEnabled默认为YES,可以滚动)
_sView.contentSize = CGSizeMake(_sView.frame.size.width * _imageArr.count, 0);
//设置翻页效果
_sView.pagingEnabled = YES;
//启动时候设置偏移量显示数组中的第二张图
_sView.contentOffset = CGPointMake(_sView.frame.size.width, 0);
//设置代理
_sView.delegate = self;
[self.view addSubview:_sView];
//往ScrollView中加图片、(循环播放,)
for (int i = 0; i<_imageArr.count; i++) {
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width * i, 0, [UIScreen mainScreen].bounds.size.width, 400)];
imgView.image = [UIImage imageNamed:_imageArr[i]];
[_sView addSubview:imgView];
}
}
- (void)createPagecontroller
{
//Pagecontroller
_pgControler = [[UIPageControl alloc]initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 100)/2, 100+200, 100, 40)];
_pgControler.numberOfPages = 4;//设置Pagecontroller的页数
_pgControler.currentPage = 0;//设置Pagecontroller的当前页
_pgControler.backgroundColor = [UIColor blackColor];
[self.view addSubview:_pgControler];
}
#pragma mark UIScrollViewDelegate
// scrollview 减速停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
if (scrollView.contentOffset.x == 0) {
//从第一张图向左滑(左边提前放了一张最后一张图,障眼法),设置偏移量使得瞬间跳到最后一张图
scrollView.contentOffset = CGPointMake(self.view.frame.size.width * (_imageArr.count - 2), 0);
} else if (scrollView.contentOffset.x == (_imageArr.count - 1)*self.view.frame.size.width){
//从最后一张图向右滑(右边提前放了一张第一张图,障眼法),设置偏移量使得瞬间跳到第一张图
scrollView.contentOffset = CGPointMake(self.view.frame.size.width, 0);
}else{
}
//pageController的currentPage
_pgControler.currentPage = scrollView.contentOffset.x / self.view.frame.size.width - 1;
}
@end
网友评论