UIScrollView Infinite Scrolling

前端 未结 10 1883
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 13:45

I\'m attempting to setup a scrollview with infinite (horizontal) scrolling.

Scrolling forward is easy - I have implemented scrollViewDidScroll, and when the contentO

10条回答
  •  独厮守ぢ
    2020-11-27 14:13

    (hope I'm posting this correctly - I'm new here!?)

    mvds was spot on - thanks - subclassing UIScrollView works perfectly - I'm yet to implement the shifting and loading of new data, but I have a UIScrollView that scrolls round in an endless loop!

    Heres the code:

    #import "BRScrollView.h"
    
    @implementation BRScrollView
    
    - (id)awakeFromNib:(NSCoder *)decoder {
        offsetAdjustment = 0;
        [super initWithCoder:decoder];
        return self;
    }
    
    - (void)setContentOffset:(CGPoint)contentOffset {
    
        float realOffset = contentOffset.x + offsetAdjustment;
    
        //This happens when contentOffset has updated correctly - there is no need for the adjustment any more
        if (realOffset < expectedContentOffset-2000 || realOffset > expectedContentOffset+2000) {
            offsetAdjustment = 0;
            realOffset = contentOffset.x;
        }
    
        float pageNumber = realOffset / 320;
        float pageCount = self.contentSize.width / 320;
    
        if (pageNumber > pageCount-4) {
            offsetAdjustment -= 3200;
            realOffset -= 3200;
        }
    
        if (pageNumber < 4) {
            offsetAdjustment += 3200;
            realOffset += 3200; 
        }
    
        //Save expected offset for next call, and pass the real offset on
        expectedContentOffset = realOffset;     
        [super setContentOffset:CGPointMake(realOffset, 0)];
    
    
    }
    
    - (void)dealloc {
        [super dealloc];
    }
    
    
    @end
    

    Notes:

    If you actually want an infinite loop, you'd need to adjust the numbers - this codes notices when you get near the edge and moves you to just beyond the middle

    My contentSize is 6720 (21 pages)

    I'm only interest in scrolling horizontally, so only save the x values and hard code the y to 0!

    Ben

提交回复
热议问题