圖片輪播器

#import "ViewController.h"oop

#define ImageCount 5atom

@interface ViewController ()<UIScrollViewDelegate>spa

{orm

    NSTimer * timer;圖片

}rem

 

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;get

@property (weak, nonatomic) IBOutlet UIPageControl *pageConterl;string

 

@endit

 

@implementation ViewControllerio

 

- (void)viewDidLoad {

    [super viewDidLoad];

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

    

    //固定的尺寸參數

    CGFloat imageW = self.scrollView.frame.size.width;

    CGFloat imageH = self.scrollView.frame.size.height;

    CGFloat imageY = 0;

    

    for (int i = 0;i<ImageCount; i++) {

        UIImageView *imageView = [[UIImageView alloc] init];

        

        //設置圖片尺寸

        CGFloat imageX = i * imageW;

        imageView.frame = CGRectMake(imageX, imageY, imageW, imageH);

        

        //圖片顯示

        imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"img_%02d",i + 1]];

        

        [self.scrollView addSubview:imageView];

    }

    

    //設置contentSize

    self.scrollView.contentSize = CGSizeMake(ImageCount * imageW, 0);

    

    //隱藏水平滾動條

    self.scrollView.showsHorizontalScrollIndicator = NO;

    

    //分頁瀏覽

    self.scrollView.pagingEnabled = YES;

    

    //設置page的總數

    self.pageConterl.numberOfPages = ImageCount;

    

    //添加定時器

    [self addTimer];

}

 

//添加定時器

-(void)addTimer

{

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

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

}

 

//移除定時器

-(void)removeTimer

{

    [timer invalidate];

    timer = nil;

}

 

//改變頁碼

-(void)changImage

{

    //增長pageControl的頁碼

    long page = 0;

    if (self.pageConterl.currentPage == ImageCount -1) {

        page = 0 ;

    }else{

        page = self.pageConterl.currentPage + 1;

    }

    //計算scrollView滾動的位置

    

    CGFloat offsetX = page * self.scrollView.frame.size.width;

    CGPoint offset = CGPointMake(offsetX, 0);

    [self.scrollView setContentOffset:offset animated:YES];

    

}

//scrollView正在滾動就會調用

-(void)scrollViewDidScroll:(UIScrollView *)scrollView

{

    //根據scrollView的滾動位置聚丁pageControl顯示第幾頁

    CGFloat scrollW = scrollView.frame.size.width;

    int page = (scrollView.contentOffset.x +scrollW*0.5)/scrollW;

    self.pageConterl.currentPage = page;

}

 

//開始拖拽時使用

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

{

    [self removeTimer];

}

//中止拖拽時使用

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

{

    [self addTimer];

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

相關文章
相關標籤/搜索