您好,欢迎来到年旅网。
搜索
您的当前位置:首页iOS scrollView循环自动滚动

iOS scrollView循环自动滚动

来源:年旅网

额外创建两个imageView

把最后一张图片添加到最前面

把第一张图片添加到最后面

-(void)setData:(FunData *)data

{

    _data = data;

    

    NSMutableArray *imageArray = [NSMutableArray array];

    [imageArray addObject:[data.imageArray lastObject]];

    [imageArray addObjectsFromArray:data.imageArray];

    [imageArray addObject:[data.imageArray firstObject]];


    float x = 0;

    

    for (NSString *urlString in imageArray)

    {

        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, 0, self.contentView.width, self.contentView.height)];

        NSLog(@"%@",urlString);

        [imageView sd_setImageWithURL:[NSURL URLWithString:urlString]];

        [self.scrollView addSubview:imageView];

        

        x += self.contentView.width;

    }

    

    self.pageControl.numberOfPages = data.imageArray.count;

    self.pageControl.currentPage = 0;

    

    self.scrollView.delegate = self;

    self.scrollView.contentSize = CGSizeMake(x, self.contentView.height);

    self.scrollView.contentOffset = CGPointMake(self.contentView.width, 0);

    self.scrollView.pagingEnabled = YES;

    self.scrollView.showsHorizontalScrollIndicator = NO;

    

    [self startScroll];

}


#pragma mark - 自动滚动

-(void)autoScroll

{

    NSInteger currentPage = self.pageControl.currentPage >=self.data.imageArray.count-1? 0:self.pageControl.currentPage+1;

    self.pageControl.currentPage = currentPage;

    CGFloat pointX = self.scrollView.width * (currentPage + 1);

    self.scrollView.contentOffset = CGPointMake(pointX, 0);

}


-(void)startScroll

{

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(autoScroll) userInfo:nil repeats:YES];

    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

    _timer = timer;

}


-(void)stopScroll

{

    [self.timer invalidate];

    self.timer = nil;

}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView

{

    NSInteger page = scrollView.contentOffset.x / scrollView.width - 1;

    self.pageControl.currentPage  = page;

    

    if (page == self.data.imageArray.count)

    {

        self.pageControl.currentPage = 0;

        [self.scrollView setContentOffset:CGPointMake(self.contentView.width, 0) animated:NO];

    }

    else if (page == -1)

    {

        self.pageControl.currentPage = self.data.imageArray.count;

        [self.scrollView setContentOffset:CGPointMake(self.contentView.width * self.data.imageArray.count, 0) animated:NO];

    }

}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

{

    [self stopScroll];

}


-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate

{

    [self startScroll];

}



因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务