Ios – How to programmatically force a scroll using UIScrollView

iosiphoneuikituiscrollview

I have a horizontal UIScrollview set up (meaning its not one that scrolls up and down but one that only scrolls left-right) and upon the app launching, I want this scrollview to scroll itself left, then right – kind of "demonstrating" its ability to scroll – and finally then stop, letting the user then take over and control the scroll manually with their finger.
Everything works – except for this on-load left-right demo-scrolling.

I'm not using Interface Builder for any of this, I'm doing everything with code:

//(this is in viewDidLoad:)
// Create the scrollView:
UIScrollView *photosScroll = [[UIScrollView alloc] initWithFrame: CGRectMake(0, 0, 320, 200)];
[photosScroll setContentSize: CGSizeMake(1240, 200)]; 
// Add it as a subview to the mainView
[mainView addSubview:photosScroll];


// Set the photoScroll's delegate: 
photosScroll.delegate = self;

// Create a frame to which to scroll:   
CGRect frame = CGRectMake(10, 10, 80, 150);
// Scroll to that frame:
[photosScroll scrollRectToVisible: frame animated:YES];

So the scrollView loads successfully and I'm able to scroll it left and right with my finger – but it doesn't do this "auto-scroll" like I was hoping it would.

  • I tried calling the scrollRectToVisible before and after adding the
    scrollView as a subview – didn't work.
  • Thinking maybe this should
    happen in loadView and not in viewDidLoad? But if so, how?

Any ideas?

Best Answer

A couple of ways to do this:

  1. Use scrollRectToVisible:animated: for a zero X value and then a largeish positive one, then set it back to your middle point. You can call the method after the scroll view is added as a subview (probably before too, but best be safe). You'll need to calculate what value of X is off-screen to the left using your contentSize and knowledge about how wide your various elements inside the scroll view are.
  2. Since you're just doing a quick animation and will give the user control, this can really be a quick-and-dirty animation, so you could use setContentOffset:animated: to force the content of the scrollview to move relative to your current view position. Move the elements right for a left scroll (positive X value), then left twice as far for a right scroll (negative X value), then set the offset back to zero.

You shouldn't put either of these in viewDidLoad or loadView; put them in viewDidAppear, which is after your scrollview is actually drawn on screen. You only care about animations when the user can see them!