Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS. How do I restrict UIScrollview scrolling to a limited extent? [duplicate]

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

like image 323
dugla Avatar asked Jun 05 '12 22:06

dugla


2 Answers

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;
}
like image 81
Vladimir Avatar answered Nov 02 '22 23:11

Vladimir


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

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

like image 22
Craig Siemens Avatar answered Nov 03 '22 00:11

Craig Siemens