How do you programmatically force scroll using UIScrollView?

I have a horizontal UIScrollview setting (this means that it is not the one that scrolls up and down, but only scrolls left and right) and when I start the application, I want this scroll to look at itself from the left, and then the right one - demonstrating "its ability scrolling - and finally stops, allowing the user to then grab and control the scroll manually with his finger. Everything works - except for this demo of scrolling left and right.

I do not use Interface Builder for any of this, I do 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 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, scrollView loads successfully, and I can scroll it left and right with my finger, but it doesn’t do this “auto scroll” as I hoped.

  • I tried calling scrollRectToVisible before and after adding scrollView as a subtitle - it didn't work.
  • Think this should be happening in loadView and not in viewDidLoad? But if so, how?

Any ideas?

+6
source share
1 answer

A few ways to do this:

  • Use scrollRectToVisible:animated: for a null value of X and then for a big positive, and then set it to its midpoint. You can call the method after the scroll view has been added as a subquery (perhaps even earlier, but best of all is safe). You will need to calculate what the X value is off the screen on the left, using contentSize and knowing how wide your various elements are inside the scroll.
  • Since you are just doing quick animations and giving the user control, it really can be fast and dirty animations, so you can use setContentOffset:animated: to make the scroll content move relative to the current position. Move the items to the right for left scrolling (positive X value), then leave twice to the desired scroll (negative X value), then set the offset back to zero.

You should not put any of them in viewDidLoad or loadView ; put them in viewDidAppear , which after your scrollview is drawn on the screen. You only care about animations when the user can see them!

+5
source

Source: https://habr.com/ru/post/899936/


All Articles