How to scroll UIScrollVIEW programmatically

I want to scroll my UIScrollView (horizontally). But when the button is pressed, it goes left to scroll. I want to scroll it 3.4 pixels, and when I click again, it scrolls another 3.4 pixels

 - (IBAction)leftScroll:(id)sender { CGPoint pt; pt.x = 1; pt.y = 0; UIScrollView *sv = (UIScrollView *)[self.view viewWithTag:5]; [sv setContentOffset:pt animated:YES]; } 

Thank you in advance for your reply.

+4
source share
4 answers

Try and set a new position manually.

Objective-c

  float width = CGRectGetWidth(scrollView.frame); float height = CGRectGetHeight(scrollView.frame); float newPosition = scrollView.contentOffset.x+width; CGRect toVisible = CGRectMake(newPosition, 0, width, height); [scrollView scrollRectToVisible:toVisible animated:YES]; 

Swift 4

 let scrollView = UIScrollView() let width: CGFloat = scrollView.frame.size.width let height: CGFloat = scrollView.frame.size.height let newPosition: CGFloat = scrollView.contentOffset.x + width let toVisible: CGRect = CGRect(x: newPosition, y: 0, width: width, height: height) scrollView.scrollRectToVisible(toVisible, animated: true) 
+18
source

You can use the [scrollView setContentOffset:CGPointMake(x, y) animated:YES]; method [scrollView setContentOffset:CGPointMake(x, y) animated:YES]; . If your scrollView scrolls horizontally, you need to set the value to x, otherwise the value is y.

+5
source

You can scroll to some point as a scroll with the following in Obj-C

 [scrollView setContentOffset:CGPointMake(x, y) animated:YES]; 

or swift

 scrollView.contentOffset = CGPoint(x: x, y: y) 

To make a slide show using UIScrollView, you arrange all the images in scroll mode, set up a repeating timer, then -setContentOffset: animated: when the timer fires.

+2
source
 UIButton *locatorbutton_frame=(UIButton *)[scrollviewoutlet viewWithTag:numberglobal]; float width = scrollviewoutlet.frame.size.width; float height = scrollviewoutlet.frame.size.height; float newPosition = scrollviewoutlet.contentOffset.x-locatorbutton_frame.frame.size.width;//+width; CGRect toVisible = CGRectMake(newPosition, 0, width, height); [scrollviewoutlet scrollRectToVisible:toVisible animated:YES]; 

I found that it works fine locatorbutton_frame - the button that I added to scrollview.

0
source

All Articles