UIScrollView
iOS Development
Swift Programming
ScrollView Automation
Mobile App Development

Programmatically scroll a UIScrollView

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

UIScrollView is normally driven by touch, but many iOS interfaces need to move it in code. Typical cases include jumping to an error message, revealing the active text field when the keyboard appears, restoring a saved position, or paging to a selected item. The core API is simple, but correct scrolling depends on layout timing and content insets.

The Three Properties That Matter

Programmatic scrolling usually revolves around three values:

  • 'contentSize, which is the total scrollable area'
  • 'bounds, which is the visible region'
  • 'contentOffset, which is the current scroll position'

The most direct way to scroll is to set the offset:

swift
1import UIKit
2
3let target = CGPoint(x: 0, y: 200)
4scrollView.setContentOffset(target, animated: true)

This moves the visible origin to the requested point. Using animation is usually better for user-facing interactions because it preserves visual context.

Scrolling to the Top or Bottom

When you want a well-defined edge position, include the adjusted insets rather than using hard-coded coordinates.

swift
1import UIKit
2
3func scrollToTop(_ scrollView: UIScrollView) {
4    let top = CGPoint(x: 0, y: -scrollView.adjustedContentInset.top)
5    scrollView.setContentOffset(top, animated: true)
6}
7
8func scrollToBottom(_ scrollView: UIScrollView) {
9    let maxY = scrollView.contentSize.height - scrollView.bounds.height + scrollView.adjustedContentInset.bottom
10    let targetY = max(-scrollView.adjustedContentInset.top, maxY)
11    scrollView.setContentOffset(CGPoint(x: 0, y: targetY), animated: true)
12}

That makes the behavior safer when safe areas, navigation bars, or automatic content inset adjustment are involved.

Scrolling a Subview Into View

Often the goal is not a raw offset but a particular control. In that case, convert the subview's rect into the scroll view's coordinate system and use scrollRectToVisible.

swift
1import UIKit
2
3func scrollSubviewIntoView(_ subview: UIView, in scrollView: UIScrollView) {
4    let targetRect = subview.convert(subview.bounds, to: scrollView)
5    scrollView.scrollRectToVisible(targetRect.insetBy(dx: 0, dy: -16), animated: true)
6}

This is especially useful for forms, validation messages, and focused input controls because it avoids manual offset math.

Wait Until Layout Is Finished

A very common source of incorrect scrolling is calculating the target position too early. Before Auto Layout finishes, frames and content size may still be wrong.

swift
1import UIKit
2
3final class ProfileViewController: UIViewController {
4    @IBOutlet private weak var scrollView: UIScrollView!
5    @IBOutlet private weak var errorLabel: UILabel!
6
7    override func viewDidLayoutSubviews() {
8        super.viewDidLayoutSubviews()
9
10        let rect = errorLabel.convert(errorLabel.bounds, to: scrollView)
11        scrollView.scrollRectToVisible(rect, animated: false)
12    }
13}

viewDidLayoutSubviews is often a better choice than viewDidLoad when the target depends on final geometry.

Keeping a Field Visible When the Keyboard Appears

One of the most common reasons to scroll programmatically is keeping the active text field visible above the keyboard. A standard pattern is to update the inset and then reveal the focused field.

swift
1import UIKit
2
3func keyboardWillShow(notification: Notification, scrollView: UIScrollView, activeField: UIView?) {
4    guard
5        let frame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
6        let window = scrollView.window
7    else {
8        return
9    }
10
11    let keyboardFrame = window.convert(frame, to: scrollView.superview)
12    scrollView.contentInset.bottom = keyboardFrame.height
13    scrollView.verticalScrollIndicatorInsets.bottom = keyboardFrame.height
14
15    if let activeField {
16        let rect = activeField.convert(activeField.bounds, to: scrollView)
17        scrollView.scrollRectToVisible(rect, animated: true)
18    }
19}

This is usually better than shifting the whole view controller, because the scroll behavior stays attached to the scrollable content.

Paging Horizontally

For paged horizontal content, compute the offset from the page width:

swift
1import UIKit
2
3func scrollToPage(_ page: Int, in scrollView: UIScrollView) {
4    let width = scrollView.bounds.width
5    let x = CGFloat(page) * width
6    scrollView.setContentOffset(CGPoint(x: x, y: 0), animated: true)
7}

This works especially well with isPagingEnabled = true.

Common Pitfalls

The most common mistake is trying to scroll before layout is complete. If frames are stale or zero, the calculated offset will be wrong.

Another problem is ignoring insets. Safe areas, keyboards, and navigation bars all affect the usable visible region, so hard-coded offsets often fail on real devices.

People also try to scroll beyond the valid range. UIScrollView clamps many values, but bad math still produces visually incorrect results.

Finally, do not confuse the scroll view's coordinate system with a subview's coordinate system. Convert rectangles before using them.

Summary

  • Use setContentOffset when you know the exact point to reveal.
  • Use scrollRectToVisible when the target is a specific subview.
  • Wait until layout is finished before calculating frames or offsets.
  • Include adjustedContentInset in top and bottom calculations.
  • For forms, combine keyboard inset updates with scrolling the active field into view.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.