轮播图

作者: moonlun | 来源:发表于2016-07-13 23:15 被阅读0次

    #import"ViewController.h"

    @interfaceViewController()

    //滑动视图UIScrollView,自带了可滑动功能

    @property(nonatomic,strong)

    UIScrollView*scrollView;

    @end

    @implementationViewController

    #define screenWidth[UIScreen mainScreen].bounds.size.width

    #define screenHeight[UIScreen mainScreen].bounds.size.height

    - (void)viewDidLoad {

    [superviewDidLoad];

    //创建初始化滑动视图

    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];

    //设置滑动试图的滑动区域contenSize

    self.scrollView.contentSize=CGSizeMake(6*screenWidth,screenHeight);

    //整屏翻转

    self.scrollView.pagingEnabled=YES;

    //边界回弹

    self.scrollView.bounces=NO;

    //设置代理,代理是负责监听滑动试图整个滑动过程的

    self.scrollView.delegate=self;

    }

    //滑动视图滑动的时候调用

    - (void)scrollViewDidScroll:(UIScrollView*)scrollView;{

    //contene)ffset是访问到了滑动视图的偏移量,包含了X和Y轴的偏移量

    //sentConteneOffset:animated:

    //{NSLog(@"偏移量,x = %f,y = %f",scrollView.contentOffset.x,scrollView.contentOffset.y);

    }

    //scrollView结束减速(停止)

    - (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView

    {

    //判断是否为最后一张

    NSIntegerindex = scrollView.contentOffset.x/screenWidth;

    //==5表示最后一张

    if(index==5) {

    [scrollViewsetContentOffset:CGPointMake(0,0)animated:NO];

    }

    //开启一个计时器

    //TimeInterval:时间间隔

    //每隔一段时间间隔,target会去执行selector这个方法

    [NSTimer

    scheduledTimerWithTimeInterval:2target:selfselector:@selector(turnToNextImage)userInfo:nilrepeats:YES];

    }

    //定时器触发的方法;跳转到下一张

    -(void)turnToNextImage

    {

    //获取当前第几张图片

    NSIntegerindex =self.scrollView.contentOffset.x/screenWidth;

    //跳转到下一张(设置偏移量)

    [self.scrollViewsetContentOffset:CGPointMake((index+1)*screenWidth,0)animated:YES];

    }

    //滑动结束时候调用

    - (void)scrollViewDidEndScrollingAnimation:(UIScrollView*)scrollView;

    {

    //现获取当前下标

    NSIntegerindex =self.scrollView.contentOffset.x/screenWidth;if(index==5) {

    [scrollViewsetContentOffset:CGPointMake(0,0)animated:NO];

    }

    }

    - (void)didReceiveMemoryWarning{

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be

    recreated.

    }

    @end

    cB

    相关文章

      网友评论

          本文标题:轮播图

          本文链接:https://www.haomeiwen.com/subject/vmvsjttx.html