我弄了半天终于弄出UIScrollView循环了,分享一下,方法感觉有点不好,要是有大侠有更好的方法指点一下。
创建了一些文件,ScrollView就是要在ScrollViewController循环的View
//_colorArray.count+2是因为需要在前后多加一个View CGSize newSize = CGSizeMake(MDefaultScrollWidth*(_colorArray.count+2), MDefaultScrollHeigh); [self.scrollView setContentSize:newSize];
我的实现方法就是在头和尾各多加一个View,头view与实现的最后一个view数据相同,尾view与实现的第一个view的数据相同:
//头View NSArray* firstNibView = [[NSBundle mainBundle] loadNibNamed:@"ScrollView"owner:self options:nil]; ScrollView* firstView = [firstNibView objectAtIndex:0]; [firstView setFrame:CGRectMake(0, 0, MDefaultScrollWidth, MDefaultScrollHeigh)]; [firstView.backgroundView setBackgroundColor:[_colorArray lastObject]]; [firstView.label setText:[NSString stringWithFormat:@"%d",5]]; [self.scrollView addSubview:firstView]; //尾view NSArray* lastNibView = [[NSBundle mainBundle] loadNibNamed:@"ScrollView"owner:self options:nil]; ScrollView* lastView = [lastNibView objectAtIndex:0]; [lastView setFrame:CGRectMake(MDefaultScrollWidth*(_colorArray.count+1), 0, MDefaultScrollWidth, MDefaultScrollHeigh)]; [lastView.backgroundView setBackgroundColor:[_colorArray objectAtIndex:0]]; [lastView.label setText:[NSString stringWithFormat:@"%d",0]]; [self.scrollView addSubview:lastView];
在加入中间要实现的View
for (int i=0; i<_colorArray.count; i++) { NSArray* nibView = [[NSBundle mainBundle] loadNibNamed:@"ScrollView"owner:self options:nil]; ScrollView* scrollView = [nibView objectAtIndex:0]; [scrollView setFrame:CGRectMake(MDefaultScrollWidth*(i+1), 0, MDefaultScrollWidth, MDefaultScrollHeigh)]; NSLog(@"%d",i); [scrollView.backgroundView setBackgroundColor:[_colorArray objectAtIndex:i]]; [scrollView.label setText:[NSString stringWithFormat:@"%d",i]]; [self.scrollView addSubview:scrollView]; }
第一次显示的时候要将ScrollView把头view移过去
self.scrollView.delegate = self; //第一次显示移到第二个view [self.scrollView scrollRectToVisible:CGRectMake(MDefaultScrollWidth, 0, MDefaultScrollWidth, MDefaultScrollHeigh) animated:NO];
最后在
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
加入方法:
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { CGFloat pageWidth = MDefaultScrollWidth; CGFloat pageHeigth = MDefaultScrollHeigh; //计算当前view的位置 int currentPage = floor((self.scrollView.contentOffset.x-pageWidth/2)/pageWidth)+1; NSLog(@"the current page==%d",currentPage); if (currentPage == 0) { //当移动到头view的时候,切换到实现的最后一个view [self.scrollView scrollRectToVisible:CGRectMake(pageWidth*[_colorArray count], 0, pageWidth, pageHeigth) animated:NO]; NSLog(@"the last image"); return; }else if(currentPage == [_colorArray count]+1){ //当移动到尾view的时候,切换到实现的第一个view [self.scrollView scrollRectToVisible:CGRectMake(pageWidth, 0, pageWidth, pageHeigth) animated:NO]; NSLog(@"the first image"); return; } }
这样就完成循环了,方法不是很好,希望大侠指正!!!
写的不是很好,把源码传上来,也许更能看懂,以后争取多写些文章练练文笔。