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

}



你可能感兴趣的:(iOS)