I have a custom-drawn view that I include in a UIScrollView that scrolls horizontally. The view draws a background with lines extending horizontally, and some different background colors. When I scroll to the far left such that the scroll view "bounces", I see gray background color. What I would like to do is to draw additional background lines and colors into that area, so that it looks like the view goes on forever, but I can't quite figure out how to do this. I've tried setting clipsToBounds to NO for all the views, and drawing in an area outside the view, but this doesn't seem to work. How can I draw in this area?
-
Have you tried creating your own scrollview (subclass UIScrollView) and implement drawRect:? Could be tricky to combine this with the original drawing implementation but that is how I would try first. – Till Apr 21 '11 at 16:03
2 Answers
I found the solution to this, at least in my case. I simply increased the size of the scroll view with an extra margin, then positioned the scroll view partly off the screen.
CGFloat scrollViewHeight = 300;
CGFloat preferredWidthOfContent = 500;
CGFloat gutterMargin = self.bounds.size.width / 2;
scrollView.frame = CGRectMake(-1 * gutterMargin, 0, self.bounds.size.width, scrollViewHeight)
scrollView.contentSize = CGSizeMake(preferredWidthOfContent + 2 * gutterMargin, scrollViewHeight);
contentView.frame = CGRectMake(0, 0, preferredWidthOfContent + 2 * gutterMargin, scrollViewHeight);
The content view has to know about the gutter margin width, and then draws the actual content in the correct place based on that. When the scrollView is "bounced", then the remainder of the content view is actually displayed.
This trick works because the scrollview is extending off the screen. If you wanted to use the same trick with a scrollview that did not touch the edges of the screen, you would have to simply place another view over the top of the scrollview to hide the extra space.

- 14,367
- 9
- 52
- 85
If you're drawing your lines in drawRect:
method, there's no way to draw them outside of the view bounds. The property clipsToBounds
only affects subviews, so, in theory, you could add a subview to your main view (the one displaying the content) with a frame that extends to the right of your view and draw the lines in that subview.
Another option is to add a subview to the scroll view and place it to the right of your main view. Then draw the lines in this subview. The scroll view will still bounce since it doesn't care whether there are still partially visible views in it, it only looks at the contentSize
property to decide when to stop scrolling.
If neither option is suitable, describe in more detail what kind of lines you're drawing and what kind of appearance you would like to achieve.

- 7,287
- 2
- 31
- 41