Custom Scroll Distance for UIScrollView

Most recently, I was trying to create a slider for users to navigate between different items. A scroll view was working fine since it implements most of the scrolling behavior I needed in my application natively. But the content I want to scroll was smaller in width and UIScrollView is designed to scroll multiples of its width. This was truly a problem. It was possible to scroll 2-3 items once a time and there were no focus, although I was looking for a one-to-one transition between different items.

There were possibilities to listen touches and calculate the positioning of the next item and scroll to it. But to be honest, I had no time to try out fancy and not-stable solutions. Instead of losing myself in the rules of UIScrollView, I wanted UIScrollView to get lost in me. Remind the rule: “Only scroll multiples of its width horizontally”. Great, so why not modifying scroll view’s size? Well, just because I want other items to be visible and lined together to give user a feeling that it is a slider.

 

Normally, that is where you stop, but there appeared a trick to make it work my way. I decided not to clip the subviews of scroll view and TA-DA! Images were lined up together and were visible even though they were not in the bounds of my scroll view. Very simple and clean solution. Inline note please: Before moving to the “how”, I want to point out there is a problem with this trick. You cannot interact with items out of the scroll view boundaries. If your items are tiny, this is a huge problem because scrolling will only be active for 50-60 pixels. Consequently, use this trick if items are at least %50-%60 of the whole screen.

Start a new window-based Xcode project. Create a view controller with a xib file. Open xib file and add a UIScrollView to the main view. Return back to the controller you created and add a property to connect UIScrollView. Return back to Interface Builder. Modify the width, height and positioning of the view. Connect controller’s scroll view to UIScrollView we created. Enable paging and uncheck “Clip Subviews”. Our scroll view is ready to be filled. On the viewDidLoad method, I’m going to add several images.

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

    [super viewDidLoad];
    int i = 0, cx = 0;

    for(;;i++){
	UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"image%d.png", i + 1]];

	if(image == nil) break;

	UIImageView *view = [[UIImageView alloc] initWithImage:image];
	view.frame = CGRectMake(cx,0, scrollView.frame.size.width, scrollView.frame.size.height);
	[scrollView addSubview:view];

	[view release];
	cx += scrollView.frame.size.width;
    }

    scrollView.contentSize = CGSizeMake(cx, scrollView.frame.size.height);
}

And finally build and run. It is going to work.