SubviewAttachingTextView icon indicating copy to clipboard operation
SubviewAttachingTextView copied to clipboard

Question: Track attachment position?

Open magonicolas opened this issue 7 years ago • 1 comments

How could I track attachment positions? I want to disable people from deleting my image and video attachment that I am inserting, I could use func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool but not sure how to keep track of my attachment positions.

Also, how can I remove an attachment?

magonicolas avatar Nov 16 '17 12:11 magonicolas

Hi Nicolas, sorry for not responding for so long – I wasn't notified about your issues being created.

Using textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool seems like a reasonable thing to do in order to prevent the user from performing certain text modifications. Do I understand correctly that by "keeping track of attachment positions" you mean tracking their character index in the text string, not their graphical location in the text view? If so, you can use NSAttributedString API such as enumerateAttribute(_:, in:, options:, using:) to enumerate values of NSAttributedStringKey.attachment in the text string (or its substring – e.g. the one identified by the range passed to you in the aforementioned delegate method) and check if there are any non-nil values. That would indicate the presence of an attachment in that substring.

To remove an attachment, simply remove the substring that corresponds to NSAttributedStringKey.attachment attribute value from the text view's attributed string using NSMutableAttributedString API such as replaceCharacters(in:, with:). You'll need to identify the substring range that the attachment occupies (it would be a single-character range corresponding to NSAttachmentCharacter) and pass an empty string as a replacement. As mentioned in the library's README, SubviewAttachingTextView/SubviewAttachingTextViewBehavior will automatically identify that the attachment is no longer present in the string and remove the subview that represents it.

I hope this answers your questions!

vlas-voloshin avatar Jan 15 '18 14:01 vlas-voloshin