views:

808

answers:

2

I have a UIScrollView with a UIView inside. I want to lock the x-axis so that the view is only scrolled vertically. How do I enable directional locking?

A: 

You'll be subclassing UIScrollView and overriding the touchesBegan:withEvent: method, touchesMoved:withEvent: method, and the touchesEnded:withEvent: method.

You'll use those methods, along with the start and end points of a touch, to calculate what kind of touch event took place: was it a simple tap, or a horizontal or vertical swipe?

If it is a horizontal swipe, you cancel the touch event.

Take a look at the source code here to learn how you might get started.

Alex Reynolds
Better to inform the scrollview of your intent I think rather than manually cancelling touches yourself. With your approach, if you begin dragging horizontally (even if by accident), you cannot then drag vertically and have it work.
Nick Farina
I was afraid someone would say this...A sure-fire way to lock an axis i'm sure, but I think I'll keep searching for a lazier way to do this. Thanks for your response though. Nick Farina solved my issue by suggesting to: First, set the UIScrollView's "contentSize" to have a width that is equal to or less than the width of the UIScrollView's frame.Next, set UIScrollView's "alwaysBounceHorizontal" to NO. This will prevent the scroll view from "rubber banding" even though you've told it there's no more horizontal content to display.
RexOnRoids
+3  A: 

First, set the UIScrollView's "contentSize" to have a width that is equal to or less than the width of the UIScrollView's frame.

Next, set UIScrollView's "alwaysBounceHorizontal" to NO. This will prevent the scroll view from "rubber banding" even though you've told it there's no more horizontal content to display.

UIScrollView *scrollView;
CGRect size = scrollView.contentSize;
size.width = CGRectGetWidth(scrollView.frame);
scrollView.contentSize = size;
scrollView.alwaysBounceHorizontal = NO;

It doesn't matter what's actually inside the scroll view.

Nick Farina
Worked. Great, and thanks very much.
RexOnRoids