Creating Circular and Infinite UIScrollViews

来源:互联网 发布:小志网络赚钱博客 编辑:程序博客网 时间:2024/05/22 17:47

 

I‘ve just finished implementing theinfitine scroll for me. In my Implementation I have UITableViewCellwith a scrollView and Navigationbuttons. The scrollView contains xviews all with the same width. views are alined horizontally andpaging is enabled.


scrollView.clipsToBounds =YES;

scrollView.scrollEnabled =YES;

scrollView.pagingEnabled =YES;

scrollView.showsHorizontalScrollIndicator= NO;

My codelogic is like thefollowing:


In my initialization functionI

create all the views (for thescrollview) and

put them into an array and

add them to the scrollView

Then I call a function that calculatesin a loop the positions for each view (each time you detect ascroll this function will need to be called too). It always takesthe first element of the array and sets the frame to (0,0,...,...),the second with (i*width,0,....,....) and so on. The functionbeeing called looks like this:


-(void)updateOffsetsOfViews{

   int xpos = 0;

   for (int i=0; i<[views count];i++) {

       UIImageView*_view = [views objectAtIndex:i];

       CGRectaFrame = _view.frame;

      aFrame.origin.x = xpos;

      aFrame.origin.y = 0.0;

       _view.frame= aFrame;

       xpos +=viewWidth;

   }

   float center = 0;

   if(fmod([views count],2) == 1){

       center =viewWidth * ([views count]-1)/2;

   }else {

       center =viewWidth * [views count]/2;

   }

   [scrollView setContentOffset:CGPointMake(center,0)];

   lastOffset = center;

}

Then (still in the initializationprocess) I add an observer


[scrollView addObserver:selfforKeyPath:@"contentOffset" options:0 context:nil];

so each time something in thescrollView changes I get the (observeValueForKeyPath)-functioncalled, which looks like this:


-(void)observeValueForKeyPath:(NSString *)keyPathofObject:(id)object  change:(NSDictionary *)changecontext:(void *)context

{

   UIImageView *_viewFirst = (UIImageView *)[viewsobjectAtIndex:0];

   if ( fmod([scrollView contentOffset].x,viewWidth) == 0.0) {

       if([scrollView contentOffset].x > lastOffset){

          [viewsremoveObjectAtIndex:0];

          [views addObject:_viewFirst];             

          [self updateOffsetsOfViews];   

       }else if([scrollView contentOffset].x < lastOffset){

          UIImageView *_viewLast =(UIImageView *)[views lastObject];

          [viewsremoveLastObject];

          [views insertObject:_viewLastatIndex:0];          

          [selfupdateOffsetsOfViews];

      }

   }

}

And in dealloc or viewDidUnload(depends on how you implement it) don't forget to remove theobserver.


[scrollView removeObserver:selfforKeyPath:@"contentOffset"];  

Hope this helps, you might notice someoverhead, but in my implementation I also support like scrolling 5pages (well... unlimited) at once and autoanimated scrolling etc.so you might see something that could be thrown away.

0 0
原创粉丝点击