首页 > 代码库 > 可以循环滚动的展示图

可以循环滚动的展示图

ViewController.h

@interface ViewController : UIViewController<UIScrollViewDelegate>
{
    NSInteger _index;
    UIPageControl *_pageCtrl;
    UIScrollView *_scrollerView;
}

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _scrollerView= [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    _scrollerView.delegate = self;
    _scrollerView.backgroundColor = [UIColor redColor];
    _scrollerView.pagingEnabled = YES;
    _scrollerView.showsHorizontalScrollIndicator = NO;
    _scrollerView.contentSize = CGSizeMake(320*6, 480);
    [self.view addSubview:_scrollerView];
    
    for (int i=0; i<6; i++) {
        NSString *name = [NSString stringWithFormat:@"%d",i];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:name]];
        imageView.frame = CGRectMake(320*i, 0, 320, 480);
        [_scrollerView addSubview:imageView];
    }
    
    _pageCtrl = [[UIPageControl alloc] initWithFrame:CGRectMake(20, 400, 280, 30)];
    _pageCtrl.backgroundColor = [UIColor grayColor];
    _pageCtrl.numberOfPages = 5;
    [self.view addSubview:_pageCtrl];
    
    //自动滑动
    [NSTimer scheduledTimerWithTimeInterval:2
                                     target:self
                                   selector:@selector(timeAction:)
                                   userInfo:nil
                                    repeats:YES];
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    int count = scrollView.contentOffset.x/320;
    //实现循环滑动
    if (count == 5) {
        //重点是这句话
        scrollView.contentOffset = CGPointMake(0, 0);
        _pageCtrl.currentPage = 0;
        
    }else {
        _pageCtrl.currentPage = count;
    }
}

- (void)timeAction:(NSTimer *)time {

    _index ++;
    if (_index == 5) {
        _index = 0;
    }
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:.5];
    _scrollerView.contentOffset = CGPointMake(_index*320, 0);
    [UIView commitAnimations];
    
    _pageCtrl.currentPage = _scrollerView.contentOffset.x/320;
}


@end


可以循环滚动的展示图