在项目中把banner图片UIImageView一张一张的放入UIScrollView中,通过设置UIScrollView的pagingEnabled属性为YES,则可以做到当用户滑动banner时图片一张一张的显示,但当用户想从第一张图到最后一张图,或者从最后一张图到第一张图的时候就会卡住,简单点的做法就是判断用户swipe的方向,然后让UIScrollView自动滑动到最后一张或者第一张,这样做在动画中又显得不够自然,一下是解决办法

  假设banner图片有3张,在banner的UIScrollView中用以下的方式进行排列

第三张第一张第二张第三张第一张

UIScrollView默认滚动到第二张图片的位置,当用户滑动到第一张时,则UIScrollView自动滚动到第4张去,同理当用户滑动到最后一张时,UIScrollView自动滚动到第二张去,这些滚动都设置动画效果为NO

代码如下

h文件

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIScrollView *mainScroll;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl; @end

m文件

#import "ViewController.h"

@interface ViewController ()<UIScrollViewDelegate>
{
CGFloat w;
NSMutableArray *imgArr;
NSMutableArray *pageArr;
} @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
w = self.view.frame.size.width;
//page的个数
pageArr = [NSMutableArray array];
for (int i = ; i <= ; i++) {
[pageArr addObject:[NSString stringWithFormat:@"%d.jpg",i]];
}
//重新获取imgView的个数,将显示的第最后一张图片放在第一张,而在最后一张放置显示的第一张图片
imgArr = [NSMutableArray array];
[imgArr addObject:pageArr[pageArr.count - ]];
for (NSString *imgSrc in pageArr) {
[imgArr addObject:imgSrc];
}
[imgArr addObject:pageArr[]];
self.mainScroll.contentSize = CGSizeMake(w*imgArr.count, );
//开始塞入图片
for (int i = ; i < imgArr.count; i++) {
NSString *imgSrc = imgArr[i];
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(i*w, , w, self.mainScroll.frame.size.height)];
[imgView setImage:[UIImage imageNamed:imgSrc]];
[self.mainScroll addSubview:imgView];
}
self.pageControl.numberOfPages = pageArr.count;
self.mainScroll.bounces = NO;
self.mainScroll.pagingEnabled = YES;
self.mainScroll.showsHorizontalScrollIndicator = NO;
self.mainScroll.showsVerticalScrollIndicator = NO;
self.mainScroll.delegate = self;
//自动将scrollView移动显示的第一张图片处
[self.mainScroll setContentOffset:CGPointMake(w, ) animated:NO];
} - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
CGFloat offsetX = scrollView.contentOffset.x;
int index = offsetX/w;
if (index == ) {
[self.mainScroll setContentOffset:CGPointMake(w*(imgArr.count-), ) animated:NO];
self.pageControl.currentPage = pageArr.count - ;
}else if (index == imgArr.count -){
[self.mainScroll setContentOffset:CGPointMake(w, ) animated:NO];
self.pageControl.currentPage = ;
}else{
self.pageControl.currentPage = index - ;
} } @end
05-17 02:49