UITextView for displaying long text?

My app displays vertically scrollable text to the user which could be as short as a single screen or as long as a book chapter: imagine something like an e-book reader which uses scrolling rather than page-turning.

A long time ago when development first started, I tried using UITextView, but the size of text that could be handled was quite limited (a figure of 32767 points seems to stick in the memory). Accordingly I came up with a custom solution in which a UIScrollView handled scrolling gestures and a custom UIView rendered just the part of the text that was visible at that time. That works, but it becomes cumbersome to add support for features such as selection handles and loupes.

18 years later, is there a more smoothly integrated way of displaying long scrollable text?

Answered by Frameworks Engineer in 892253022

Hi!

UITextView has come a long way, and uses the viewport based virtual scrolling mechanism provided by TextKit. You can take a look at these WWDC sessions to learn more about it.

-- Tarun

Accepted Answer

Hi!

UITextView has come a long way, and uses the viewport based virtual scrolling mechanism provided by TextKit. You can take a look at these WWDC sessions to learn more about it.

-- Tarun

Yes — this is exactly what TextKit 2 was built for, and it largely retires the custom UIScrollView + tile-rendering approach.

Since iOS 15, UITextView is backed by TextKit 2 (NSTextLayoutManager) by default. The key piece for your case is NSTextViewportLayoutController: TextKit 2 lays out only the text fragments inside the visible viewport (plus a small over-scroll margin), not the whole document. So a long chapter doesn't get laid out up front, and you're no longer fighting the old coordinate ceiling the way TextKit 1 / a single giant canvas did. You get selection handles, the loupe, link interaction, Dynamic Type, etc. for free, because it's a real UITextView.

One important gotcha: a UITextView only stays on TextKit 2 if you never touch the legacy NSLayoutManager. Accessing the .layoutManager property triggers an automatic, permanent downgrade to TextKit 1 (and you lose viewport layout). Use .textLayoutManager / .textContentManager instead, or create it explicitly with init(usingTextLayoutManager: true).

For truly book-length (not chapter-length) content you may still segment documents, but for a scrolling chapter a TextKit 2 text view should handle it smoothly without the custom scroll plumbing.

If it helps to see the moving parts in a real project, I recently open-sourced a TextKit 2 editor in Objective-C — it leans on the resolve-at-render / viewport model and might save you some spelunking: TextKit2-Editor

UITextView for displaying long text?
 
 
Q