Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll UIScrollVIew programmatically

Tags:

objective-c

I want to scroll my UIScrollView (horizontally). But when the button is pressed it goes the left most side of the scroll view. I want to scroll it 3,4 pixels and when I press 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];         
}

Thanks in advance for your answer

like image 244
OOkhan Avatar asked Nov 28 '22 21:11

OOkhan


1 Answers

Try it 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)
like image 141
Hardeep Singh Avatar answered Dec 18 '22 00:12

Hardeep Singh