8

What is the best way to set limits on the left/right scrolling of a UIScrollView. I would have thought this would be easy but all my attempts have been unsuccessful.

So, to be clear, I need a solution that will allow me to programmatically limit the scrolling extent whenever I need to during the use of my app. This will most often be in response to changes in the data being displayed.

Thanks,
Doug

dugla
  • 12,774
  • 26
  • 88
  • 136

3 Answers3

11

You can control the size of contents using contentSize property of scroll view. If that is not sufficient for you (e.g. you need to limit scroll area to some arbitrary region in the middle of your contents) you can force contentOffset to be in required limit in the delegate method of your scroll view.

Basically code may look like:

- (void) scrollViewDidScroll:(UIScrollView*)scroll{
    CGPoint offset = scroll.contentOffset;

    // Check if current offset is within limit and adjust if it is not
    if (offset.x < minOffsetX) offset.x = minOffsetX;
    if (offset.y < minOffsetY) offset.y = minOffsetY;
    if (offset.x > maxOffsetX) offset.x = maxOffsetX;
    if (offset.y > maxOffsetY) offset.y = maxOffsetY;

    // Set offset to adjusted value
    scroll.contentOffset = offset;
}
Vladimir
  • 170,431
  • 36
  • 387
  • 313
  • Vladimir, I actually found an approach that will work that is similar to your solution. I override layoutSubViews in my scrollView subclass and do the clamping there, similar to what you are doing in the scrollViewDelegate. I am actually not sure which approach is preferable. If I recall the delegate method fires after layoutSubviews. Any thoughts? – dugla Jun 06 '12 at 00:17
  • This will cause problem when paging is enabled, paging will not work properly. – moligaloo Dec 02 '14 at 07:40
7

All you would need to do is change the content size for the scroll view with the following code.

[scrollView setContentSize:CGSizeMake(width, height)];

Craig Siemens
  • 12,942
  • 1
  • 34
  • 51
  • In my case I cannot alter the content in anyway. I am doing a visualization app and content size is fundmental to the visualization. What I am looking for is something analogues to minimumZoomScale and maximumZoomScale. Changing these values has no effect on the content. – dugla Jun 05 '12 at 22:55
-5

I went with my approach of placing pan constraints in my overloaded layoutSubviews method.

Pseudo-code:

Calculate criteria for constraining pan
if (pan-constraint-is-met) {

    Calculate pan-limit
    [self setContentOffset:limitedContentOffset];

}
dugla
  • 12,774
  • 26
  • 88
  • 136