//
// ViewController.m
//轮播图
//
// Created by lanou on 16/7/13.
// Copyright © 2016年lanou. All rights reserved.
//
#import"ViewController.h"
@interfaceViewController()
#define screenWidth [UIScreen mainScreen].bounds.size.width
#define screenHeight [UIScreen mainScreen].bounds.size.height
/*
UIPageControl numOfPages currentPage
*/
//滑动视图UIScrollView,自带了可滑动功能
@property(nonatomic,strong)UIScrollView*scrollView;
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
//创建初始化滑动视图
//[UIScreen mainScreen].bounds]包含了屏幕的尺寸
self.scrollView= [[UIScrollViewalloc]initWithFrame:[UIScreenmainScreen].bounds];
for(NSIntegeri =0;i <5;i++){
//根据i循环创建UIImageView,再添加到滑动视图scrollView上面
UIImageView*imageView = [[UIImageViewalloc]initWithFrame:CGRectMake(i*screenWidth,0,screenWidth,screenHeight)];
NSString*imageName =nil;//[NSString stringWithFormat:@"%ld.jpg",i+1];
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会去执行selector这个方法
[NSTimerscheduledTimerWithTimeInterval:2target:selfselector:@selector(turnToNextImage)userInfo:nilrepeats:YES];
}
//定时器触发的方法:跳转到下一张图片
-(void)turnToNextImage
{
//先获取当前图片是第几张
NSUIntegerindex =self.scrollView.contentOffset.x/screenWidth;
//跳转到下一张(设置偏移量)
[self.scrollViewsetContentOffset:CGPointMake((index+1)*screenWidth,0)animated:YES];
}
//滑动视图滑动的时候调用
- (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];
}
}
//滑动动画结束的时候调用
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView*)scrollView{
//先获取当前下标,判断是否为最后一张
NSIntegerindex = scrollView.contentOffset.x/screenWidth;
//==5表示最后一张图片,如果是最后一张图片就切换到第0张(设置偏移量为0,0)
if(index ==5){
[scrollViewsetContentOffset:CGPointMake(0,0)animated:NO];
}
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
}
@end
网友评论