//
//ViewController.m
//轮播图
//
//Created by lanouhn on 16/7/13.
//Copyright © 2016年lanouhn. All rights
reserved.
//
//
#import"ViewController.h"
@interfaceViewController()
#define screenWidth [UIScreenmainScreen].bounds.size.width
#define screenHeight[UIScreen mainScreen].bounds.size.height
/*UIPageControlnumOfPages
currentPage
*/
@property(nonatomic,strong)UIPageControl*pageControl;
//滑动视图UIScrollView,自带了可滑动功能
@property(nonatomic,strong)UIScrollView*scrollView;
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
//创建初始化滑动视图
//[UIScreen
mainScreen].bounds]:包含了屏幕的尺寸
self.scrollView= [[UIScrollViewalloc]initWithFrame:[UIScreenmainScreen].bounds];
for(NSIntegeri =0; i <6; i++) {
//根据i循环创建UIImageView。再添加到滑动视图scrollView上面
UIImageView*imageView = [[UIImageViewalloc]initWithFrame:CGRectMake(i*screenWidth,0,screenWidth,screenHeight)];
NSString*imageName =nil;
if(i ==5) {
imageName =@"1.jpg";
}else{
imageName = [NSStringstringWithFormat:@"%ld.jpg",i+1];
}
//加载响应的图片
UIImage*image = [UIImageimageNamed:imageName];
//设置图片
imageView.image= image;
//将imageView添加到滑动视图上去
[self.scrollViewaddSubview:imageView];
}
//添加滑动视图到屏幕上面
[self.viewaddSubview:self.scrollView];
//设置滑动视图区域contentSize
self.scrollView.contentSize=CGSizeMake(6*screenWidth,screenHeight);
//整屏翻转
self.scrollView.pagingEnabled=YES;
//边界回弹
self.scrollView.bounces=NO;
//设置代理,代理是负责监听滑动视图整个滑动过程的
self.scrollView.delegate=self;
//开启一个定时器
//TimeInterval:时间间隔
//每隔一定的时间间隔,target回去执行selecto这个方法
[NSTimerscheduledTimerWithTimeInterval:2target:selfselector:@selector(turnToNextImage)userInfo:nilrepeats:YES];
}
//定时器触发的方法:跳转到下一张图片
-(void)turnToNextImage
{
//先获取当前图片是第几张
NSIntegerindex =self.scrollView.contentOffset.x/screenWidth;
//跳转到下一张
[self.scrollViewsetContentOffset:CGPointMake((index+1)*screenWidth,0)animated:YES];
self.pageControl= [[UIPageControlalloc]initWithFrame:CGRectMake(130,665,150,20)];
self.pageControl.numberOfPages=5;
[self.viewaddSubview:self.pageControl];
}
//滑动动画结束的时候调用
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView*)scrollView;
{
//先获取当前下标
NSIntegerindex = scrollView.contentOffset.x/screenWidth;
//是最后一张就设置偏移量为0,0
if(index ==5) {
[scrollViewsetContentOffset:CGPointMake(0,0)animated:NO];
}
}
//滑动视图滑动的时候调用
- (void)scrollViewDidScroll:(UIScrollView*)scrollView
{
//contentOffset是访问到了滑动视图的偏移量,包含了x和y轴的偏移量
//setContentOffset:animated:
//NSLog(@"偏移量.x = %f,偏移量.y = %f",scrollView.contentOffset.x,scrollView.contentOffset.y);
}
// scrollView结束减速(停止)
- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView
{
//判断是否为最后一张
NSIntegerindex = scrollView.contentOffset.x/screenWidth;
//==5表示最后一张图片,如果是最后一张图片就切换到第0张图片(设置偏移量为0,0)
if(index ==5) {
[scrollViewsetContentOffset:CGPointMake(0,0)animated:NO];
self.pageControl.currentPage=0;
}else{
self.pageControl.currentPage= index;
}
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
}
@end