看到很多應(yīng)用里都有圖片的輪播,正好前段時間做的項目中也用到了猴仑。
就想到要寫一篇關(guān)于輪播的文章法严,來共享一下這個比較好用的圖片輪播方法村砂。
適用于輪播圖片比較多的情況烂斋,希望大家多多評論。
有什么問題也可以提出來一起討論。 廢話不多說汛骂,下面直接上代碼-------
<pre><code>
#import "ViewController.h"
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
@interface ViewController () <UIScrollViewDelegate>
//實例化scrollview
- (void)createScrollView;
//scrollView添加子視圖
- (void)addChildViewAboutMyScroll;
//展示
@property (nonatomic,strong) UIScrollView *myScroll;
@end
@implementation ViewController {
/**總頁數(shù)*/
NSInteger _wholePages;
/**當(dāng)前頁*/
NSInteger _currentPage;
}
- (void)viewDidLoad {
[super viewDidLoad];
/**實例化scrollview*/
[self createScrollView];
/**scrollview添加子視圖*/
[self addChildViewAboutMyScroll];
}
//實例化scrollview
- (void)createScrollView {
self.myScroll = [[UIScrollView alloc] initWithFrame:self.view.bounds];
/**打開按頁滾動*/
self.myScroll.pagingEnabled = YES;
/**設(shè)置代理*/
self.myScroll.delegate = self;
/**初始化總頁數(shù)與當(dāng)前顯示頁*/
_wholePages = 6;
_currentPage = 1;
/**設(shè)置起始顯示點*/
self.myScroll.contentOffset = CGPointMake(_currentPage * SCREEN_WIDTH, 0);
/**設(shè)置可滾動的最大大小*/
self.myScroll.contentSize = CGSizeMake(3 * SCREEN_WIDTH, 0);
/**添加到view上*/
[self.view addSubview:self.myScroll];
}
//scrollView添加子視圖
- (void)addChildViewAboutMyScroll {
for (int i = 0; i < 3; i++) {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i*SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
/**初始化顯示三張圖片*/
imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"海賊%02d",i] ofType:@"jpg"]];
[self.myScroll addSubview:imageView];
}
}
//數(shù)據(jù)刷新
- (void)refreshData {
[self updateSubImageView:(_currentPage - 1) with:0];
[self updateSubImageView:_currentPage with:1];
[self updateSubImageView:(_currentPage + 1) with:2];
}
/**
abstact:根據(jù)傳入數(shù)據(jù)修改相對應(yīng)子視圖
imageName:拼接圖片名字
index:子視圖下標(biāo)
*/
- (void)updateSubImageView:(NSInteger)imageName with:(NSInteger)index {
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"海賊%02ld",((imageName + _wholePages) % _wholePages) ] ofType:@"jpg"]];
UIImageView *imageView = self.myScroll.subviews[index];
/**修改子視圖顯示圖片*/
imageView.image = image;
}
#pragma mark ------------scrollview協(xié)議相關(guān)-----------
//滾動視圖停止?jié)L動
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
/**計算當(dāng)前顯示的是第幾頁*/
NSInteger subViewIndex = scrollView.contentOffset.x / SCREEN_WIDTH;
switch (subViewIndex) {
case 0:
{
_currentPage = ((_currentPage - 1) % _wholePages);
[self refreshData];
}
break;
case 2:
{
_currentPage = ((_currentPage + 1) % _wholePages);
[self refreshData];
}
break;
default:
break;
}
/**刷新ContentOffSet*/
[self.myScroll setContentOffset:CGPointMake(SCREEN_WIDTH, 0) animated:NO];
}
</pre></code>