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

余生颓废 提交于 2019-12-07 01:42:35

问题


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


回答1:


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;
}



回答2:


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

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




回答3:


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];

}


来源:https://stackoverflow.com/questions/10905953/ios-how-do-i-restrict-uiscrollview-scrolling-to-a-limited-extent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!