iOS - 关于轮播图的实现实例

来源:互联网 发布:nginx 经典书籍 编辑:程序博客网 时间:2024/06/06 06:54

在此,因为只有一个页面,所以没有管理定时器。如果在实际开发项目中,则需要把定时器在合适的位置 kill 掉。本博客只作为一个参考的小 Demo 。。。代码如下:

// 屏幕尺寸

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

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


// 照片的数量

#define    PHOTOCOUNT  4


// 轮播时间的间隔

#define    MOVETIME    2.0


#import "ViewController.h"



@interface ViewController () <UIScrollViewDelegate> {

    UIScrollView *_scroll;

    UIPageControl *_page;

}



@end



@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.


    UIScrollView *scrollView = [[UIScrollViewalloc] init];

    scrollView.frame =self.view.bounds;

    scrollView.backgroundColor = [UIColorblackColor];

    scrollView.delegate =self;

    scrollView.pagingEnabled =YES;

    scrollView.bounces =NO;

    [self.viewaddSubview:scrollView];

    _scroll = scrollView;

    

    UIPageControl *page = [[UIPageControlalloc] init];

    page.frame =CGRectMake((WIDTH-100)/2,HEIGHT-50,100, 20);

    page.backgroundColor = [UIColorblackColor];

    page.numberOfPages =PHOTOCOUNT;

    page.currentPageIndicatorTintColor = [UIColorwhiteColor];

    page.pageIndicatorTintColor = [UIColorredColor];

    [self.viewaddSubview:page];

    _page = page;

    

    

    for (NSInteger i =0; i<PHOTOCOUNT+1; i++) {

        UIImageView *imageView = [[UIImageViewalloc] init];

        imageView.frame =CGRectMake(WIDTH*i,0, WIDTH,HEIGHT);

        imageView.contentMode =UIViewContentModeScaleAspectFit;

        NSString *name = [NSStringstringWithFormat:@"%ld.jpg",i];

        if (PHOTOCOUNT == i) {

            name = @"0.jpg";

        }

        imageView.image = [UIImageimageNamed:name];

        [scrollView addSubview:imageView];

 

    }

    

    scrollView.contentSize =CGSizeMake(WIDTH*(PHOTOCOUNT+1),0);

    

    NSTimer *timer = [NSTimertimerWithTimeInterval:MOVETIMEtarget:selfselector:@selector(movePhoto)userInfo:nilrepeats:YES];

    

    [[NSRunLoopcurrentRunLoop] addTimer:timerforMode:NSRunLoopCommonModes];

    

}


- (void)movePhoto {

    

    NSInteger contentOffSet_x =_scroll.contentOffset.x;

    

    if (contentOffSet_x >=PHOTOCOUNT*WIDTH) {

        

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

        _page.currentPage =0;


    }else {

        

        [_scrollsetContentOffset:CGPointMake(contentOffSet_x+WIDTH,0) animated:YES];

        _page.currentPage =_scroll.contentOffset.x/WIDTH + 1;

    }

    

    if (contentOffSet_x == (PHOTOCOUNT-1)*WIDTH) {

        _page.currentPage =0;

    }

    

}


OK,一个简易的轮播图就到此结束。。。





0 0
原创粉丝点击