1. 程式人生 > >最簡單的無限輪播圖

最簡單的無限輪播圖

有人說iOS輪播圖很簡單,我覺得他們說的很多

本來不打算寫demo的,然而我發現我找的一些資源都不是太好,不是邏輯不夠清晰明瞭就是程式碼量多的嚇人,本來一個很簡單的東西搞得這麼複雜

那麼,來看看我的輪播圖(直接程式碼+demo)

1,

ViewController.m檔案屬性

@interfaceViewController ()<UIScrollViewDelegate>

{

UIScrollView *scroll;

NSArray *imageAry;//所有的圖片

NSArray *selectImageAry;//選中的三張圖片源

NSInteger index;//當前選中

}

2,新增UIScrollView第一步已經協議過

-(void)addScrlloView

{

//圖片源

imageAry=@[@"http://img.taopic.com/uploads/allimg/120727/201995-120HG1030762.jpg",@"http://pic4.nipic.com/20091217/3885730_124701000519_2.jpg",@"http://img.zcool.cn/community/01711b59426ca1a8012193a31e5398.gif",@"http://www.taopic.com/uploads/allimg/140421/318743-140421213T910.jpg"]

;//網上找的圖片地址

scroll =[[UIScrollViewalloc]initWithFrame:Frame(0,80,WIDTH,HEIGHT -80)];

scroll.backgroundColor=[UIColorredColor];

scroll.contentSize =CGSizeMake(WIDTH*3,0);

scroll.delegate =self;

scroll.pagingEnabled =YES;

[self.viewaddSubview:scroll];

scroll.contentOffset =CGPointMake(WIDTH,0);

for (int i=0

; i<3; i++) {

UIImageView *imageView=[[UIImageViewalloc]initWithFrame:Frame(i*WIDTH,0,WIDTH,HEIGHT -80)];

imageView.tag=i+1;

imageView.backgroundColor=[UIColorgreenColor];

[scroll addSubview:imageView];

}

[selfloadImage];//圖片載入

}

3,圖片載入

#pragma mark - 載入圖片

- (void)loadImage

{

//index預設為0也就是第一次載入的時候

if (index==0) {//當前選中資料來源第一張圖片

selectImageAry=@[imageAry[imageAry.count-1],imageAry[index],imageAry[index+1]];

}elseif (index==imageAry.count-1){//當前選中資料來源最後一張圖片

selectImageAry=@[imageAry[index-1],imageAry[index],imageAry[0]];

}else{//正常情況

selectImageAry=@[imageAry[index-1],imageAry[index],imageAry[index+1]];

}

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

UIImageView *imageView=[scrollviewWithTag:i+1];

[imageView sd_setImageWithURL:[NSURLURLWithString:selectImageAry[i]]];

}

scroll.contentOffset =CGPointMake(WIDTH,0);//載入圖片後再回到中間

}

4,代理

#pragma mark - scrollView代理

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {

if (aScrollView ==scroll) {

int x = aScrollView.contentOffset.x;

//往下翻一張

if(x >= (2*scroll.frame.size.width)) {

if (index==imageAry.count-1) {

index=0;

}else{

index+=1;

}

[self loadImage];

}

//往上翻

if(x <= 0) {

if (index==0) {

index=imageAry.count-1;

}else{

index-=1;

}

[self loadImage];

}

}

//scroll.contentOffset =CGPointMake(WIDTH, 0);

}


無限輪播圖完成(效果很完美,不存在效果不佳的情況)