原理就是ScrollView中同时只有1、2、3张图片,每次翻动结束后,重新设置这三张图片,如1、2、3,原来是2,向右翻动结束减速后将1、2、3换成2、3、4,由于是结束滚动后替换的,所以看上去跟平滑滚动是一样的
#import "ViewController.h"
@implementation ViewController
{
UIScrollView *_mainScrollView;
NSMutableArray *_imagePathArray;
NSInteger _currentIndex;
CGFloat _width;
CGFloat _height;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_width = self.view.frame.size.width;
_height = self.view.frame.size.height;
self.view.backgroundColor = [UIColor whiteColor];
_mainScrollView = [[UIScrollView alloc] init];
_mainScrollView.frame = CGRectMake(0, 0, _width , _height);
_mainScrollView.delegate = self;
_mainScrollView.pagingEnabled = YES;
_mainScrollView.bounces = NO;
_mainScrollView.showsHorizontalScrollIndicator = NO;
_mainScrollView.contentSize = CGSizeMake(_width*3, _height);
[self.view addSubview:_mainScrollView];
_imagePathArray = [[NSMutableArray alloc] init];
for(int i=1;i<7;i++)
{
NSString *path = [NSString stringWithFormat:@"%@/%d.jpg",[[NSBundle mainBundle] resourcePath],i];
[_imagePathArray addObject:path];
}
_currentIndex = 0;
[self loadImageView];
}
- (void)loadImageView
{
// 移除之前加载的
for(UIView *view in _mainScrollView.subviews)
{
[view removeFromSuperview];
}
// 当前页
UIImage *currentImage = [[UIImage alloc] initWithContentsOfFile:[_imagePathArray objectAtIndex:_currentIndex]];
UIImageView *currentImageView = [[UIImageView alloc] initWithImage:currentImage];
currentImageView.frame = CGRectMake(_width, 0, _width, _height);
[_mainScrollView addSubview:currentImageView];
// 左侧页
UIImage *preImage = [[UIImage alloc] initWithContentsOfFile:_currentIndex-1<0?[_imagePathArray lastObject]:[_imagePathArray objectAtIndex:_currentIndex-1]];
UIImageView *preImageView = [[UIImageView alloc] initWithImage:preImage];
preImageView.frame = CGRectMake(0, 0, _width, _height);
[_mainScrollView addSubview:preImageView];
// 右侧页
UIImage *nextImage = [[UIImage alloc] initWithContentsOfFile:_currentIndex+1==_imagePathArray.count?[_imagePathArray firstObject]:[_imagePathArray objectAtIndex:_currentIndex+1]];
UIImageView *nextImageView = [[UIImageView alloc] initWithImage:nextImage];
nextImageView.frame = CGRectMake(_width*2, 0, _width, _height);
[_mainScrollView addSubview:nextImageView];
[_mainScrollView setContentOffset:CGPointMake(_width, 0)];
}
//翻页
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
NSLog(@"scrollView.contentOffset.x = %.0f",scrollView.contentOffset.x);
int index = scrollView.contentOffset.x/_width;
if(index == 0)
{
_currentIndex = _currentIndex-1<0?_imagePathArray.count-1:_currentIndex-1;
[self loadImageView];
}
if(index == 2)
{
_currentIndex = _currentIndex+1==_imagePathArray.count?0:_currentIndex+1;
[self loadImageView];
}
}
@end