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

3

7

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

Pelagic answered 5/6, 2012 at 22:33 Comment(0)
P
-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];

}
Pelagic answered 7/6, 2012 at 14:14 Comment(0)
P
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;
}
Pomelo answered 5/6, 2012 at 22:51 Comment(2)
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?Pelagic
This will cause problem when paging is enabled, paging will not work properly.Truditrudie
M
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)];

Macready answered 5/6, 2012 at 22:39 Comment(1)
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.Pelagic
P
-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];

}
Pelagic answered 7/6, 2012 at 14:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.