Let Readers Pause Auto-Scrolling In SwiftUI Chat
A chat screen follows new messages nicely until someone scrolls up to read an earlier reply. Then another message arrives and the screen takes them straight back to the bottom.
The message has arrived. It has not acquired custody of the reader’s scroll position.
The useful fix is a small policy: follow new content until the reader takes control, then stay paused until they choose Latest. Keep that decision separate from geometry, and distinguish a new message from another chunk of text added to the same message.
We’ll build that policy with SwiftUI’s iOS 18 scroll APIs. They are established APIs, still useful with the current SDK. The two Swift blocks below belong together in an iOS app target; they were checked in Swift 6 mode with the installed Swift 6.4.2 compiler. The downloadable project adds a small demonstration screen, a keyboard fixture and the verification code. It has Receive and Grow buttons so the behavior is easy to try without a chat server.
Decide who owns the scrolling
There are several reasonable chat layouts. A messaging app might follow the bottom, while an assistant might place the latest question at the top. The Stack Overflow question about grouping a question and its replies already has an accepted solution for that second layout. We are building the first one, with an explicit pause policy.
The question about chat scrolling, streamed text and keyboard behavior gets closer to our example. It has one answer, though no accepted answer as of October 23, 2026. We will make the reader-intent and message-identity rules explicit.
These questions keep recurring: the older automatic-scrolling question has more than 61,000 cumulative views, and a September 2026 question describes difficulties with initial positioning and prepending history. Both are answered. The latter’s history-restoration problem is separate from what this example promises.
Our policy is intentionally conservative:
| Event | Result |
|---|---|
| Open the conversation | Start at the latest message and follow incoming content. |
| Begin a touch scroll, or press Pause | Stop automatic following. |
| Receive a new ID while paused | Append it and count it once. |
| Replace text for an existing ID | Update the row without adding to the count. |
| Finish scrolling, even at the bottom | Remain paused. |
| Press Latest | Resume following, request the bottom, and reset the local count. |
Events are processed in order on the main actor. A message processed before the pause takes effect still belongs to the preceding following mode.
That last pair is a product choice. Some apps resume automatically when the user reaches the bottom. Here, we require a deliberate command. A keyboard resize, a short conversation or a changing height estimate cannot quietly switch the policy back on.
The badge means new messages received while paused. It is not an unread receipt, a visibility measurement or proof that someone read the text. Pressing Latest resets the badge because the reader resumed following, not because we observed every row on screen.
Keep identity and intent in one small owner
An incoming message supplies a stable ID and the complete current text for that ID. New IDs append in arrival order. Existing IDs replace text in place, which also handles streamed responses when the upstream layer assembles each text snapshot.
import Foundation
import Observation
nonisolated struct ChatMessage: Identifiable, Equatable, Sendable {
let id: String
var text: String
}
@MainActor @Observable
final class ChatSession {
private(set) var messages: [ChatMessage]
private(set) var followsLatest = true
private(set) var newWhilePaused: Set<String> = []
private(set) var scrollRequest = UUID()
init(messages: [ChatMessage] = []) {
precondition(Set(messages.map(\.id)).count == messages.count)
self.messages = messages
}
// New IDs append; existing IDs replace text in place.
func receive(_ message: ChatMessage) {
if let index = messages.firstIndex(where: { $0.id == message.id }) {
guard messages[index] != message else { return }
messages[index] = message
} else {
if !followsLatest { newWhilePaused.insert(message.id) }
messages.append(message)
}
if followsLatest { scrollRequest = UUID() }
}
func pause() {
followsLatest = false
}
func resume() {
followsLatest = true
newWhilePaused.removeAll()
scrollRequest = UUID()
}
}
The store is main-actor isolated because its mutations drive this screen. A network adapter should deliver accepted snapshots to that actor; it should not regenerate the ID for every token. Repeating an identical snapshot does nothing. Updating an existing message doesn’t add another entry to newWhilePaused.
scrollRequest is a change token, not a message ID or a queue. Several updates before the next SwiftUI pass can collapse into one request to reach the current bottom. That is sufficient for this policy. If a gesture pauses the reader before the view processes a pending request, the view will check the current intent again.
This is a small in-memory conversation, not a message database. Lookup is linear in the retained array. The example does not reorder messages, delete them, paginate history or resolve out-of-order revisions. Keep those responsibilities in the app’s existing message store. For a long conversation, use a bounded loaded window and a tested history-loading strategy rather than retaining every message indefinitely.
Make every request respect the pause
Keith Harrison’s default-scroll-anchor article explains why initial position, size changes and alignment of short content are different decisions. Majid’s scroll-phase walkthrough explains how to distinguish touch interaction from programmatic scrolling. Combining those mechanisms gives us a reader-controlled screen:
import SwiftUI
@MainActor
struct ChatReader: View {
let session: ChatSession
var body: some View {
VStack(spacing: 0) {
HStack {
Text(session.followsLatest
? "Following latest"
: "New while paused: \(session.newWhilePaused.count)")
.font(.subheadline)
.accessibilityIdentifier("reader-status")
Spacer()
Button(session.followsLatest ? "Pause" : "Latest") {
if session.followsLatest { session.pause() }
else { session.resume() }
}
.buttonStyle(.bordered)
.accessibilityIdentifier("reader-control")
}
.padding()
ScrollViewReader { proxy in
ScrollView {
LazyVStack(spacing: 10) {
ForEach(session.messages) { message in
Text(message.text)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(12)
.background(.blue.opacity(0.12),
in: RoundedRectangle(cornerRadius: 12))
.id(message.id)
.accessibilityIdentifier("message-\(message.id)")
}
}
.scrollTargetLayout()
.padding(.horizontal)
.padding(.vertical, 8)
}
.accessibilityIdentifier("conversation")
.defaultScrollAnchor(.bottom, for: .alignment)
.defaultScrollAnchor(
session.followsLatest ? .bottom : nil, for: .sizeChanges
)
.onScrollPhaseChange { _, phase in
if phase == .tracking || phase == .interacting {
session.pause()
}
}
.onChange(of: session.scrollRequest, initial: true) { _, _ in
// Recheck intent when SwiftUI processes the request.
guard session.followsLatest else { return }
if let lastID = session.messages.last?.id {
proxy.scrollTo(lastID, anchor: .bottom)
}
}
.scrollDismissesKeyboard(.interactively)
}
}
}
}
The initial scroll and later requests share the same guarded onChange action. Its initial: true argument also runs the action when the view first appears. ScrollViewReader supplies the proxy, and scrollTo(lastID, anchor: .bottom) aligns the last message with the bottom of the viewport. An empty conversation simply has no target yet.
The role-specific anchor modifier handles the remaining layout choices. Alignment puts a short conversation at the bottom. Size changes use a bottom anchor only while following, including when the keyboard changes the available height; paused mode removes that explicit bottom preference.
Removing the preference is not a command to freeze every pixel. Changes above the reader, a rotation, a new text size or inserted history can still change layout. It prevents our following policy from deliberately pulling the view toward the newest content. We’ll test the narrower case of appending messages and growing an offscreen last message.
Scroll phases let us pause as a touch begins tracking or interacting, before waiting for the gesture to finish. A touch that starts tracking but never becomes a long drag can therefore pause following too. That tradeoff favors keeping control with the reader. We do not interpret .animating as a user gesture, and .idle does not resume following.
The visible Pause button matters as well. A VoiceOver focus change is not the same thing as a touch scroll phase. A labeled control lets someone pause without depending on that gesture detection. Real assistive-technology interaction still needs testing in the finished app; the presence of a button is not an accessibility certification.
When content arrives, onChange checks followsLatest again before making the scroll request. A request created while following cannot bypass a pause that occurs before this action handles it. Requests run inside the action, never during the reader’s content builder. They use no animation, so each streamed update does not launch another animated journey.
There is a reason for using an explicit initial request here. In testing, a separate bottom initial anchor still moved the first conversation update in the receive-then-pause case. A bound bottom ScrollPosition also continued moving content after the Pause label had changed. The version above passed those boundaries without either setting. Test the actual row position: a correctly updated label can conceal an incorrectly moving conversation.
Don’t turn a lazy estimate into permission
It is tempting to derive the whole policy from “within twelve points of the bottom.” That measurement can be useful for presentation. It is a poor substitute for remembering whether the reader chose to pause.
WWDC26’s lazy-stack session explains that offscreen sizes and positions are estimated, and that layout changes after appearance can disturb scrolling. We therefore keep geometry out of the decision to resume. The article’s screen doesn’t use an offset observer or a timed retry loop.
Each message has one immediate row, a stable ID and its text available when SwiftUI lays it out. The count and following state live outside the lazy rows, so row eviction does not discard them. Our lazy-stack article covers those layout concerns in more detail.
A streamed message deliberately changes height. This sample follows growth at the bottom and allows an offscreen last message to grow while the reader is elsewhere. It does not promise a stable line-level anchor when the message currently being read changes, or when an image above it finishes loading. Reserve image dimensions where possible and test those cases separately.
Connect it to a real conversation
Create one ChatSession per open conversation, keep it in the owning view’s @State, and pass it to ChatReader(session:). When replacing the entire conversation, replace that owner and give the reader a new view identity so the scroll view and its initial request reset too. Don’t reuse one session across unrelated conversation IDs.
The download keeps incoming-content controls outside the article’s reader. Receive adds a new identity; Grow replaces the last message with a longer snapshot. Its draft field exercises keyboard resizing but does not send anything. Our chat-composer article covers the actual send button and keyboard-safe layout.
Decide separately what sending a message means. If sending should return to the latest content, explicitly call resume() as part of that user action. An unrelated incoming message should never make that choice on the user’s behalf. If many tokens arrive per frame, coalesce them in your existing streaming layer; this example establishes interaction behavior, not a throughput benchmark.
Verify the interruption, not just the happy path
The useful test starts halfway through the conversation. Choose a visible message, record its screen position, receive another message, then grow the offscreen last message. The chosen row should stay put, the count should rise once, and Latest should return to the bottom.
The downloadable checks cover identity replacement, duplicate snapshots, repeated pauses, an initially empty conversation and requests created before a pause. Native UI tests cover following appends and same-ID growth, arrival during an actual drag, explicit resume, a short conversation, keyboard presentation, and larger Dynamic Type. Reflow preserves the chosen mode; it is not claimed to preserve the exact line being read.
The exact examples passed Swift 6 compilation and model checks with the installed Xcode 27.2 Release Candidate (27B48) and Swift 6.4.2, targeting iOS 18. Ten native UI tests passed in each of ordinary and default MainActor isolation on the iOS 27.0 Simulator. Those include pressing Pause before another append, growing the new last message, and receiving a message immediately before Pause. The normal demonstration also passed checks for accessibility hit regions, descriptions and traits. Physical-device behavior, an iOS 18 runtime and actual VoiceOver use remain separate checks.
This policy earns its place by making a small promise clear: new content can request a scroll while following is enabled; the reader decides when that permission returns after a pause.