UIScrollView
UIScrollView represents a view that can scroll, called a scroll view. When the content inside it is larger than the view itself, the user drags with a finger to see the rest. Dragging, the momentum scrolling after release, bouncing back after reaching an end, and the scroll indicators are all handled by the system with no code needed.
A scroll view does not measure the subviews inside it. The app must tell it how large the content is: align the four edges of the content with contentLayoutGuide using constraints, or write contentSize directly. Read the scroll position from contentOffset; the scroll event fires when it changes.
UITextView and UICollectionView are both scroll views and have all the members on this page.
All lengths and positions are in pt.
Inheritance: EventTarget → NSObject → UIResponder → UIView → UIScrollView
For how to build a scrolling view controller, what to check when it will not scroll, and how to make carousels and "load more at the bottom", see the guide Building a scrolling view.
Constructor
Creates a scroll view. Its size is 0, and so is its content area.
Instance properties
Also inherits the properties of UIView. Inherited properties commonly used with scroll views are bounds, backgroundColor, and keyboardLayoutGuide.
Position and content size:
| Property | Description |
|---|---|
contentOffset | The current scroll position |
contentSize | The size of the content area |
contentInset | Extra space around the content |
adjustedContentInset read-only | The space actually in effect, including what the system adds for the safe area |
contentInsetAdjustmentBehavior | Whether the system automatically adds space for the safe area |
contentLayoutGuide read-only | A reference for constraints, representing the content area |
frameLayoutGuide read-only | A reference for constraints, representing the visible area |
contentAlignmentPoint | How content smaller than the visible area is placed |
Behavior switches:
| Property | Description |
|---|---|
isScrollEnabled | Whether the user can drag |
bounces | Whether it can be pulled further after reaching an end |
bouncesHorizontally | Whether it bounces horizontally |
bouncesVertically | Whether it bounces vertically |
alwaysBounceVertical | Can be pulled vertically even when the content is less than a screen |
alwaysBounceHorizontal | Can be pulled horizontally even when the content is less than a screen |
isPagingEnabled | Page by page |
isDirectionalLockEnabled | One direction per drag |
scrollsToTop | Scrolls back to the top when the status bar is tapped |
delaysContentTouches | Determines whether a touch is a scroll before handing it to buttons inside |
canCancelContentTouches | Whether pressing on a button and then moving can turn into a scroll |
transfersHorizontalScrollingToParent | Hands horizontal scrolling to the outer scroll view at the end |
transfersVerticalScrollingToParent | Hands vertical scrolling to the outer scroll view at the end |
allowsKeyboardScrolling | Whether a hardware keyboard can scroll it |
decelerationRate | How far it slides after release before stopping |
keyboardDismissMode | Whether to dismiss the keyboard when the user drags |
Scroll indicators:
| Property | Description |
|---|---|
showsVerticalScrollIndicator | Whether to show the indicator when scrolling vertically |
showsHorizontalScrollIndicator | Whether to show the indicator when scrolling horizontally |
indicatorStyle | The indicators' color |
verticalScrollIndicatorInsets | The vertical indicator's distance from the edges |
horizontalScrollIndicatorInsets | The horizontal indicator's distance from the edges |
scrollIndicatorInsets | Both indicators' distance from the edges (deprecated since iOS 13) |
automaticallyAdjustsScrollIndicatorInsets | Whether the system adjusts the indicators' distance for the safe area |
indexDisplayMode | When the index bar is shown |
Zooming:
| Property | Description |
|---|---|
zoomScale | The current zoom scale |
minimumZoomScale | The minimum zoom scale |
maximumZoomScale | The maximum zoom scale |
bouncesZoom | Whether zooming beyond the range springs back |
isZooming read-only | Whether it is zooming |
isZoomBouncing read-only | Whether it is springing back into the zoom range |
isZoomAnimating read-only | Whether a zoom animation is running |
Current state and gestures:
| Property | Description |
|---|---|
isTracking read-only | Whether a finger is pressed on it |
isDragging read-only | Whether the user is dragging |
isDecelerating read-only | Whether the content is still sliding after release |
isScrollAnimating read-only | Whether a setContentOffset() animation is running |
panGestureRecognizer read-only | The gesture recognizer for dragging |
pinchGestureRecognizer read-only | The gesture recognizer for two-finger pinching |
directionalPressGestureRecognizer read-only | The gesture recognizer for arrow keys |
Instance methods
Also inherits the methods of UIView, such as addSubview() and convertRect().
| Method | Description |
|---|---|
setContentOffset() | Scrolls to a given position, optionally animated |
scrollRectToVisible() | Scrolls the shortest distance to make a rectangle fully visible |
flashScrollIndicators() | Flashes the indicators briefly |
setZoomScale() | Changes the zoom scale, optionally animated |
zoomToRect() | Zooms so a rectangle fills the visible area |
stopScrollingAndZooming() | Immediately stops any scrolling and zooming in progress |
Events
Listen with addEventListener().
| Event | When it fires |
|---|---|
scroll | The position changed. Fires for user scrolling, momentum scrolling, and writes from code |
dragbegin | The user started dragging |
beforedragend | The moment the user lifts their finger after dragging. A listener can change where the content stops |
dragend | The user lifted their finger |
deceleratebegin | The content kept sliding after release |
decelerateend | The content came to a complete stop |
scrollanimationend | The setContentOffset() animation ended |
scrolltotop | After the user tapped the status bar and it scrolled back to the top |
adjustedcontentinsetchange | adjustedContentInset changed |
traitchange | The traits changed; inherited from UIView |
Rules shared by the eight scroll events other than beforedragend:
- Events carry no data. The event object has only
typeandtarget. Read the position fromcontentOffsetand the state fromisDraggingandisDecelerating. When the callback runs, these read the latest values at that moment. - None can be canceled. Scrolling is driven by the system, which does not wait for an answer from JS: while a finger drags, the content moves first, and only afterward does the system notify JS. JS cannot stop or cancel a scroll.
- They fire after the fact. When the callback runs, the scroll view's state is already the new one. For example, reading
isDeceleratingin adragendcallback gives the actual result of "whether it is still sliding after release". - They fire after the current JS finishes running. A callback is never called in the middle of an assignment.
- No overhead without listeners. A scroll view with no listeners for any scroll event does not call into JS when it scrolls.
- Unrecognized event names do not throw. They are treated as custom events and fire only when you dispatch them yourself with
dispatchEvent(). So a misspelled event name (such asscrol) gives no warning; the listener is simply never called.
When the user drags and releases, the order is dragbegin → dragend → deceleratebegin → decelerateend, with scroll firing repeatedly throughout (verified by testing). If the content has already stopped when the finger lifts, the last two events do not fire (not verified in the simulator).
beforedragend is different: it fires on the spot the moment the finger lifts, before dragend, carrying the velocity at release and the stopping position the system computed, and the position a listener writes is where the content stops. It cannot be canceled.
Three basic concepts
A scroll view's properties revolve around three quantities.
Content area (contentSize)
┌───────────────────┐ ─┐
│ │ │ contentOffset.y
│ │ │ (distance already scrolled)
│┌─────────────────┐│ ─┘
││ ││
││ Visible area ││ the part actually seen on screen
││ (size of bounds)││
│└─────────────────┘│
│ │
│ │
└───────────────────┘| Concept | What it is | Corresponding property |
|---|---|---|
| Visible area | The rectangle the scroll view itself occupies on screen | Width and height of bounds |
| Content area | The rectangle all the content occupies, usually larger than the visible area | contentSize |
| Offset | How far the top-left corner of the content area has moved out relative to the top-left corner of the visible area | contentOffset |
The maximum scroll distance in a direction equals the content area's size minus the visible area's size (plus any space the system adds; see Safe area). If the content area is not larger than the visible area, that direction cannot scroll.
Content area size
There are two ways to state the content area's size:
| Approach | How | When to use |
|---|---|---|
| Constraints | Align the four edges of the container holding the content with contentLayoutGuide. The content area is as large as the container | Recommended. The content area follows automatically as content is added or removed |
| Write it directly | scroller.contentSize = new CGSize(width, height) | When subviews are positioned with frame. You must write it again when the content changes |
Do not use both at once. With constraints, the content area's size is computed only after the system completes layout: reading contentSize right after activating the constraints gives the old value; call layoutIfNeeded() on the view controller's root view first, then read it.
The other reference, frameLayoutGuide, represents the visible area. In whichever direction the size equals it, that direction cannot scroll.
Safe area
The safe area is the region of the screen not obscured by the notch, rounded corners, or the home indicator at the bottom.
When a scroll view fills the screen, the system by default adds space above and below the content automatically, so the first and last lines rest within the safe area. While scrolling, content still passes under the notch and the home indicator. This has two consequences:
- With the content at the very top,
contentOffset.yis not0but a negative number equal to the height of the top space. - To get the actual space, read
adjustedContentInset, which equals the app'scontentInsetplus what the system adds automatically.adjustedcontentinsetchangefires when the space changes.
The space and negative offset when filling the screen are as iOS defines them and are not verified in the simulator. The acceptance tests assert the opposite case: when the scroll view is entirely within the safe area, the system adds no space, and adjustedContentInset.top equals contentInset.top.
Whether the system adds space is determined by contentInsetAdjustmentBehavior.
Scrolling and JS
Reading the position and changing views in a scroll callback is normal usage, for example changing the title bar's opacity by scroll distance, or loading the next page when reaching the bottom. This rests on three measured facts:
scrollevents do not pile up. Scrolling that happens while a previousscrollhas not yet fired does not queue another event; when the callback runs, it reads the latest position.- One property read or one property write takes a few microseconds each (measured: 1.3–7 µs per read or write).
- One real swipe lasting 1819 ms fired
scroll100 times (simulator, Debug build).
scroll callbacks and UI updates run one after another on the same thread; for background, see How the runtime works.
However many views you put in a scroll view, that many views are created; it does not create only the ones visible on screen. Measured: creating a view takes about 4 µs, writing a property 2–7 µs, creating a constraint about 10 µs, and one addSubview() about 12 µs. For very many rows (hundreds or more), the total time and memory to create all rows at once has no measurement data. To create only the visible rows, use UICollectionView.
Examples
A scrolling page with 40 lines of text
Starting from a blank app, make a page that scrolls up and down, containing 40 lines of text.
application.addEventListener('sceneconnect', (e) => {
const win = new UIWindow(e.scene);
const page = new UIViewController();
page.view.backgroundColor = 'systemBackground';
win.rootViewController = page;
win.makeKeyAndVisible();
const scroller = new UIScrollView();
scroller.translatesAutoresizingMaskIntoConstraints = false;
page.view.addSubview(scroller);
const column = new UIStackView();
column.translatesAutoresizingMaskIntoConstraints = false;
column.axis = 'vertical';
column.spacing = 12;
scroller.addSubview(column);
for (let i = 1; i <= 40; i++) {
const label = new UILabel();
label.text = `Line ${i}`;
column.addArrangedSubview(label);
}
const content = scroller.contentLayoutGuide;
const frame = scroller.frameLayoutGuide;
NSLayoutConstraint.activateConstraints([
scroller.topAnchor.constraintEqualToAnchor(page.view.topAnchor),
scroller.bottomAnchor.constraintEqualToAnchor(page.view.bottomAnchor),
scroller.leadingAnchor.constraintEqualToAnchor(page.view.leadingAnchor),
scroller.trailingAnchor.constraintEqualToAnchor(page.view.trailingAnchor),
column.topAnchor.constraintEqualToAnchor(content.topAnchor),
column.bottomAnchor.constraintEqualToAnchor(content.bottomAnchor),
column.leadingAnchor.constraintEqualToAnchor(content.leadingAnchor),
column.trailingAnchor.constraintEqualToAnchor(content.trailingAnchor),
column.widthAnchor.constraintEqualToAnchor(frame.widthAnchor),
]);
});Effect
- "Line 1", "Line 2", … are arranged from top to bottom; 40 lines do not fit on one screen.
- Dragging up and down moves the content with the finger. After release, the content slides a little further before stopping.
- After reaching the very top or bottom, it can be pulled a little further, and springs back on release.
- A thin indicator appears on the right while scrolling and disappears after stopping.
- It cannot be dragged left or right.
This code has not been run as a whole in the simulator. The same structure has been run in the acceptance tests, which assert that the content area's height equals the sum of the row heights plus spacing and that the content area's width equals the visible area's width. Dragging, momentum, bouncing, and the indicator are default system behavior, swiped through by hand during acceptance.
Note: The line
column.translatesAutoresizingMaskIntoConstraints = falsemust not be omitted. Without it, the content area is 0, nothing is shown, and the console shows no error; see Content not showing.
Corresponding iOS API
| ObjC | JS |
|---|---|
[[UIScrollView alloc] init] | new UIScrollView() |
sv.contentOffset = CGPointMake(0, 30) | sv.contentOffset = new CGPoint(0, 30) |
[sv setContentOffset:p animated:YES] | sv.setContentOffset(p, { animated: true }) |
[sv scrollRectToVisible:r animated:YES] | sv.scrollRectToVisible(r, { animated: true }) |
[sv flashScrollIndicators] | sv.flashScrollIndicators() |
sv.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever | sv.contentInsetAdjustmentBehavior = 'never' |
sv.indicatorStyle = UIScrollViewIndicatorStyleBlack | sv.indicatorStyle = 'black' |
sv.decelerationRate = UIScrollViewDecelerationRateFast | sv.decelerationRate = 'fast' |
sv.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag | sv.keyboardDismissMode = 'onDrag' |
sv.pagingEnabled = YES | sv.isPagingEnabled = true |
sv.contentLayoutGuide | sv.contentLayoutGuide |
[sv setZoomScale:2 animated:YES] | sv.setZoomScale(2, { animated: true }) |
- scrollViewDidScroll: | The scroll event |
- scrollViewWillBeginDragging: | The dragbegin event |
- scrollViewWillEndDragging:withVelocity:targetContentOffset: | The beforedragend event. Write the stopping position to the event object's targetContentOffset |
- scrollViewDidEndDragging:willDecelerate: | The dragend event. Read isDecelerating instead of willDecelerate |
- scrollViewWillBeginDecelerating: | The deceleratebegin event |
- scrollViewDidEndDecelerating: | The decelerateend event |
- scrollViewDidEndScrollingAnimation: | The scrollanimationend event |
- scrollViewDidScrollToTop: | The scrolltotop event |
- scrollViewDidChangeAdjustedContentInset: | The adjustedcontentinsetchange event |
sv.delegate | Not needed; listen for the events above |
Comparison with the browser
This table is only for people familiar with the web to look up correspondences; the rest of the page does not depend on it.
| Web | UIScrollView | Difference |
|---|---|---|
An element with overflow: scroll | new UIScrollView() | The content area's size must be stated with constraints or contentSize; subviews are not measured automatically |
clientWidth / clientHeight | bounds.width / bounds.height | |
scrollWidth / scrollHeight | contentSize.width / contentSize.height | |
scrollLeft / scrollTop | contentOffset.x / contentOffset.y | With safe area space, the very top is negative |
scrollTo({ top, behavior: 'smooth' }) | setContentOffset(point, { animated: true }) | |
scrollIntoView() | scrollRectToVisible(rect) | Takes a rectangle, not an element |
The scroll event | The scroll event | Neither carries the position; neither can be canceled |
The scrollend event | decelerateend, scrollanimationend, and dragend with isDecelerating false | There is no single unified event |
scroll-snap-type | isPagingEnabled, or changing the stopping position in beforedragend | isPagingEnabled can stop only at whole multiples of the visible area |
overscroll-behavior: none | bounces = false |
See also
- Building a scrolling view: page skeleton, what to check when it will not scroll, horizontal scrolling, carousels, stopping on whole rows, loading more, the keyboard
UIStackView: the container holding the content in the exampleUIView: inherited members;bounds,convertRect(), background color, and rounded corners are thereUICollectionView: lists with large amounts of data, creating only the rows visible on screenUITextView: multiline input, also a scroll view- Structs:
CGPoint,CGSize,CGRect,UIEdgeInsets