iOS scrollView循环自动滚动

来源:互联网 发布:java重定向跳转 编辑:程序博客网 时间:2024/05/16 11:38

额外创建两个imageView

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

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

-(void)setData:(FunData *)data

{

    _data = data;

    

    NSMutableArray *imageArray = [NSMutableArrayarray];

    [imageArray addObject:[data.imageArraylastObject]];

    [imageArray addObjectsFromArray:data.imageArray];

    [imageArray addObject:[data.imageArrayfirstObject]];


    float x =0;

    

    for (NSString *urlStringin imageArray)

    {

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

        NSLog(@"%@",urlString);

        [imageView sd_setImageWithURL:[NSURLURLWithString:urlString]];

        [self.scrollViewaddSubview: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;

    

    [selfstartScroll];

}


#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 = [NSTimerscheduledTimerWithTimeInterval:2target:selfselector:@selector(autoScroll)userInfo:nilrepeats:YES];

    [[NSRunLoopmainRunLoop] addTimer:timerforMode:NSRunLoopCommonModes];

    _timer = timer;

}


-(void)stopScroll

{

    [self.timerinvalidate];

    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.scrollViewsetContentOffset:CGPointMake(self.contentView.width,0) animated:NO];

    }

    elseif (page == -1)

    {

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

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

    }

}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

{

    [selfstopScroll];

}


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

{

    [selfstartScroll];

}



0 0
原创粉丝点击