How to embed views into UITextView without getting a huge cursor

I want to add an image view to a UITextView. I have a few requirements:


1. The image takes up the entire width of the editor. It basically acts as a paragraph break and fills all the space between paragraphs.

2. It should not be possible to place the cursor on the row of the image; the cursor should ignore the image entirely.

3. The image should retain its position in the text.


I can think of a few approaches, but they all seem to fail one of my requirements


Option 1: Use NSTextAttachment

I can make a large text attachment that occupies the full width of the editor. This ensures that the attachment will always be placed on its own line, but does not prevent the cursor from being placed on that line. That ends up being a problem, because the cursor ends up the height of the image. This looks bad, and also causes all sorts of problems when UITextView tries to scroll the cursor to be visible but the cursor is taller than the visible area. The user never expects to type on the line containing the image; they would type either above or below it, so I'd like to disallow it being placed there at all.


Option 2: Use NSTextContainer.exclusionPaths

I can set up an exclusion path that causes text to flow right around my content. This makes the cursor behave as expected, but there's no way to make the exclusion paths flow with the text; when I add more text above the image, the text starts flowing underneath. I'd have to update the exclusion paths after every key press, and that seems like a recipe for terrible performance.


Option 3: Multiple text containers

I can add multiple text containers to the layout manager and put each text segment in its own text view. Then I can put the image between two adjacent text views and everything is happy. This works great on macOS, but on iOS, UITextView completely disables editability if you have multiple text views attached to a single layout manager. The content becomes read-only. Dead end.


Option 4: Something with control characters, maybe?

TextKit has various APIs around control characters. Is there some way to embed a control character in the text, and have the text view treat it somewhat like a newlne that has really large advancement? And then later, I could ask the layout manager where that character was and float an image view over the top of it? This seems like a promising option, but I'm not familiar enough with the APIs around control characters to be sure what's possible here.

  • I'm facing the same dilemma. What did you end up using?

Add a Comment