Contents

UITextAttachmentViewProviderReusePolicy

An option set that controls whether a text view reuses attachment view providers when scrolling or editing.

Declaration

struct UITextAttachmentViewProviderReusePolicy

Overview

By default, when content scrolls out of the visible area, UITextView removes the attachment view from the view hierarchy. NSTextAttachmentViewProvider itself persists, but the text view may recreate its view when the content returns. Editing the paragraph containing an attachment has a more significant effect: Because NSTextLayoutFragment is immutable, the text view replaces the existing fragment, discarding and recreating any NSTextAttachmentViewProvider instances it holds. For attachments with views like a media player, a drawing canvas, or a focused control, either behavior can cause views to flicker or lose their state.

To reuse providers instead of recreating them, register a reuse policy for your view provider subclass:

textView.register(
    [.onScrollingOutOfViewport, .onEditingInlineParagraphs],
    forTextAttachmentViewProviderType: MyAttachmentViewProvider.self
)

You can use onScrollingOutOfViewport or onEditingInlineParagraphs on their own, or combine them to cover both scrolling and editing. Once registered, the reuse policy applies to every instance of that view provider subclass for as long as the text view exists.

Use onScrollingOutOfViewport to keep an attachment view in the view hierarchy when its content scrolls out of the visible area — when it scrolls back into view, the text view reuses the existing view instead of recreating it, preserving states like first responder status and media playback position. Use onEditingInlineParagraphs to keep a provider when someone edits the paragraph containing it; on the next layout pass, the text view reuses it instead of creating a new one, which prevents visible flicker when someone types near an attachment.

Topics

Creating a reuse policy

Specifying reuse policy options

See Also

Managing attachment view reuse