Scrolling Area Limit in UIScrollView

I have a UIScrollView that scrolls through a fairly large UIView.

At certain points in time, I want to limit the area in which the user can scroll. For example, I can only allow them to view the bottom quarter of the view.

I can limit the scope by overriding scrollViewDidScroll and then calling setContentOffset if the view scrolls too far. But in this way, I cannot get it back as smoothly as a UIScrollView does when scrolling outside of a UIView.

Is there a better way to limit the scroll area in a UIScrollView?

+7
iphone uiscrollview
source share
3 answers

I would change the contentSize property in the scroll view to the size of the area you want, so that the user can scroll through it and edit the frame.origin of the subtitle that contains the upper left border you want (0, 0) relative to the scroll view. For example, if your view has a height of 800 points and you want to show the bottom quarter, set the height of the contentSize to 200 and set the y-component view.frame.origin to -600.

+17
source share

I found something that works for me. It allows you to scroll to point 0,0, but not further:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView { if (scrollView.contentOffset.x <= -1) { [scrollView setScrollEnabled:NO]; [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES]; [scrollView setScrollEnabled:YES]; } } 

You can do the same for top, bottom or right (x or y)

+3
source share

Another approach is to override the UIScrollView method:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event .

Returning YES will allow the user to scroll. NO refund.

NOTE. . This will disable all touches on any views embedded inside the UIScrollView that pointInside returns NO to. Useful if the area you do not want to scroll has no interaction.


This example allows UIScrollView to scroll through a UIScrollView when a user scrolls through a UITableView . (A UITableView and two UIViews nested inside a UIScrollView )

 - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { for (UIView *subview in self.subviews) { if ([subview pointInside:[self convertPoint:point toView:subview] withEvent:event] && ![subview isKindOfClass:[UITableView class]]) { return NO; } } return YES; } 
0
source share

All Articles