视图的循环现实一般采用的是412341的方法,先面试例子
#import "ViewController.h"
#define imageWidth 300
#define imageHeight 450
@interface ViewController ()<UIScrollViewDelegate>
{
NSArray * _sourceArray;
UIScrollView * _scrollView;
UIPageControl * _pageControl;
}
@end
@implementation ViewController
-(void)loadView{
[super loadView];
}
- (void)viewDidLoad
{
[super viewDidLoad];
_sourceArray = [NSArray arrayWithObjects:@"A.png",@"B.png",@"C.png",@"E.png", @"F.png",@"G.png",@"H.png",@"I.png",@"J.png",@"K.png",@"L.png",@"M.png",nil];
_scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(10, 20, imageWidth, imageHeight)];
_scrollView.delegate = self;
_scrollView.pagingEnabled = YES;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.contentSize = CGSizeMake(imageWidth*([_sourceArray count]+2), imageHeight);
[self.view addSubview:_scrollView];
UIImageView * firstImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, imageWidth, imageHeight)];
firstImage.image = [UIImage imageNamed:[_sourceArray lastObject]];
[_scrollView addSubview:firstImage];
for (int i = 1; i <= [_sourceArray count]; i++) {
UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(i*imageWidth, 0, imageWidth, imageHeight)];
imageView.image = [UIImage imageNamed:[_sourceArray objectAtIndex:i - 1]];
[_scrollView addSubview:imageView];
}
UIImageView * lastImage = [[UIImageView alloc]initWithFrame:CGRectMake(([_sourceArray count]+1)*imageWidth, 0, imageWidth, imageHeight)];
lastImage.image = [UIImage imageNamed:[_sourceArray objectAtIndex:0]];
[_scrollView addSubview:lastImage];
[_scrollView scrollRectToVisible:CGRectMake(imageWidth, 0, imageWidth, imageHeight) animated:NO];
_pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, _scrollView.frame.origin.y + _scrollView.frame.size.height - 20, imageWidth, 20)];
_pageControl.numberOfPages = _sourceArray.count;
_pageControl.currentPage = 0;
_pageControl.enabled = YES;
[self.view addSubview:_pageControl];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
int currentPage = scrollView.contentOffset.x/imageWidth;
if (currentPage == [_sourceArray count]+1) {
[_scrollView scrollRectToVisible:CGRectMake(imageWidth, 0, imageWidth, imageHeight) animated:NO];
_pageControl.currentPage = 0;
}else if (currentPage == 0){
[_scrollView scrollRectToVisible:CGRectMake(imageWidth*([_sourceArray count]), 0, imageWidth, imageHeight) animated:NO];
_pageControl.currentPage = _sourceArray.count - 1;
}else{
_pageControl.currentPage = currentPage - 1;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
上面就是实现的所有代码,主要就是用到了scrollview的一个代理方法,和scrollview的一个scrollRectToVisible:方法。