Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically scroll a UIScrollView

People also ask

How do I scroll programmatically in Swift?

If you want to programmatically make SwiftUI's ScrollView move to a specific location, you should embed a ScrollViewReader inside it. This provides a scrollTo() method that can move to any view inside the parent scrollview, just by providing its anchor.

How do you scroll on a storyboard?

You can scroll the scrollview in the Storyboard / Interface builder! Select the view inside scrollview in Document Outline, then scroll using your mouse or trackpad, you can see the view move.

What is Scrollview contentSize?

contentSize is the size of the content within the UIScrollView and how long it can be within scrollView . Sometimes this is dynamic like pagination or static like a contact list. This might be changing at runtime as well. This can be set programmatically as well.


You can scroll to some point in a scroll view with one of the following statements in Objective-C

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

or Swift

scrollView.setContentOffset(CGPoint(x: x, y: y), animated: true)

See the guide "Scrolling the Scroll View Content" from Apple as well.

To do slideshows with UIScrollView, you arrange all images in the scroll view, set up a repeated timer, then -setContentOffset:animated: when the timer fires.

But a more efficient approach is to use 2 image views and swap them using transitions or simply switching places when the timer fires. See iPhone Image slideshow for details.


If you want control over the duration and style of the animation, you can do:

[UIView animateWithDuration:2.0f delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
    scrollView.contentOffset = CGPointMake(x, y);
} completion:NULL];

Adjust the duration (2.0f) and options (UIViewAnimationOptionCurveLinear) to taste!


I'm amazed that this topic is 9 years old and the actual straightforward answer is not here!

What you're looking for is scrollRectToVisible(_:animated:).

Example:

extension SignUpView: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        scrollView.scrollRectToVisible(textField.frame, animated: true)
    }
}

What it does is exactly what you need, and it's far better than hacky contentOffset

This method scrolls the content view so that the area defined by rect is just visible inside the scroll view. If the area is already visible, the method does nothing.

From: https://developer.apple.com/documentation/uikit/uiscrollview/1619439-scrollrecttovisible


Another way is

scrollView.contentOffset = CGPointMake(x,y);

With Animation in Swift

scrollView.setContentOffset(CGPointMake(x, y), animated: true)

Swift 3

let point = CGPoint(x: 0, y: 200) // 200 or any value you like.
scrollView.contentOffset = point

scrollView.setContentOffset(CGPoint(x: y, y: x), animated: true)