看到很多应用里都有图片的轮播,正好前段时间做的项目中也用到了。
就想到要写一篇关于轮播的文章,来共享一下这个比较好用的图片轮播方法。
适用于轮播图片比较多的情况,希望大家多多评论。
有什么问题也可以提出来一起讨论。 废话不多说,下面直接上代码-------
<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 {
/**总页数*/
NSInteger _wholePages;
/**当前页*/
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;
/**设置代理*/
self.myScroll.delegate = self;
/**初始化总页数与当前显示页*/
_wholePages = 6;
_currentPage = 1;
/**设置起始显示点*/
self.myScroll.contentOffset = CGPointMake(_currentPage * SCREEN_WIDTH, 0);
/**设置可滚动的最大大小*/
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];
}
}
//数据刷新
- (void)refreshData {
[self updateSubImageView:(_currentPage - 1) with:0];
[self updateSubImageView:_currentPage with:1];
[self updateSubImageView:(_currentPage + 1) with:2];
}
/**
abstact:根据传入数据修改相对应子视图
imageName:拼接图片名字
index:子视图下标
*/
- (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协议相关-----------
//滚动视图停止滚动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
/**计算当前显示的是第几页*/
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>