一开始对相册轮播没有太好的思路,后来发现可以通过前后各加一张照片实现,原理为第一张前面放一张最后一张照片,最后一张后面放一张第一张照片
//这里新建一个数组来实现对原图片名数组前后各加一张的效果
NSMutableArray *dataSource = [[NSMutableArray alloc] initWithArray:array];
[dataSource insertObject:[array lastObject] atIndex:0];
[dataSource addObject:[array firstObject]];
//定义一个scrollView属性
_scrollView = (UIScrollView *)[[UIScrollView alloc] initWithFrame:self.bounds];
_scrollView.pagingEnabled = YES;
_scrollView.tag = 100;
_scrollView.delegate = self;
[self addSubview:_scrollView];
[_scrollView release];
//将每张图片加在一个小的scrollView上,在把小的scrollView放到大的scrollView上
for (int i = 0; i < dataSource.count; i++) {
if ([dataSource[i] isKindOfClass:[NSString class]]) {
UIScrollView *newScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(i * self.frame.size.width, 0, self.frame.size.width, self.frame.size.height)];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:newScrollView.bounds];
imageView.image = [UIImage imageNamed:[dataSource objectAtIndex:i]];
[newScrollView addSubview:imageView];
[imageView release];
[_scrollView addSubview:newScrollView];
[newScrollView release];
}
}
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.contentSize = CGSizeMake(self.frame.size.width *dataSource.count, 0);
[_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width, 0)];
//在结束减速方法里实现照片轮播的功能
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//_count是定义的一个属性,用来接收原数组的元素个数,也就是外面给的照片张数
//做两个判断,一个是当滑到最后一张的时候跳到视图第一张,另一个是反向滑到第一张的时候跳到最后一张
if (scrollView.contentOffset.x / scrollView.frame.size.width > _count) {
[scrollView setContentOffset:CGPointMake(scrollView.frame.size.width, 0)];
}
if (scrollView.contentOffset.x / scrollView.frame.size.width < 1) {
[scrollView setContentOffset:CGPointMake(scrollView.frame.size.width * _count, 0)];
}
}
思路很简单,如果想明白了应该很容易实现,还可以添加NSTimer实现自动轮播的效果,这里就不赘述了