What's the best way to have non-trivially-sized views scroll with text in a UITextView?

I've got a note editor view in my app that's built around a UITextView. At the top of the text view, it displays some metadata about the note, like location of the note (it's an e-reader app - think highlighting text and adding a note to it). I want this metadata to be able to scroll out of view if you scroll down in the text view. But it shouldn't simply be text in the text view - it's a UIView that takes the full width of the text view, with some UILabels in it. The height is on the order of 60 points tall.

What's the best way to achieve this? Should the view that contains the labels be in a text attachment? Or should it be a subview of the UITextView? Or should I do something custom like make it a subview of the view that contains the UITextView and watch the UITextView's scroll position and apply a transform to move it to match?

Answered by Frameworks Engineer in 892329022

Hi!

NSTextAttachmentViewProvider was built exactly for this! Use a NSTextAttachment and connect an NSTextAttachmentViewProvider to it. Check out the sample app where we show something similar: https://developer.apple.com/documentation/UIKit/enriching-your-text-in-text-views

To add on to the sample, you'll have to restrict selections into the attachments so that someone editing this text view will not be able to remove the metadata.

-- Tarun

Accepted Answer

Hi!

NSTextAttachmentViewProvider was built exactly for this! Use a NSTextAttachment and connect an NSTextAttachmentViewProvider to it. Check out the sample app where we show something similar: https://developer.apple.com/documentation/UIKit/enriching-your-text-in-text-views

To add on to the sample, you'll have to restrict selections into the attachments so that someone editing this text view will not be able to remove the metadata.

-- Tarun

A different way to achieve this is by doing what's talked about here: https://developer.apple.com/forums/thread/833073

What's the best way to have non-trivially-sized views scroll with text in a UITextView?
 
 
Q