📜 ⬆️ ⬇️

UITextView with pictures

Recently there was a need to give users the ability to add articles from the iPhone ʻa with photos randomly placed inside the text. Unfortunately, sdk does not provide such functionality, so I had to reinvent the wheel.

Initially, looking for solutions, I came across this possibility when sending e-mail, it uses a certain component of UITextContentView, which can be perfectly used, paste photos from the clipboard there and edit as you like. The problem arose with the receipt of these photos back to the program, the undocumented contentAsHTMLString method returned the content in HTML format, but the links to the pictures were of the form webkit-fake-url, I could not get a picture with such a link.

I want to share my solution to the problem (thanks to the user [info] igrick for advice in implementation)

Implemented as follows: UIScrollView is located at the root, UITextView is added to it (MyTextView in the example - the scrolling function is disabled inside the field), when inserting an image, UIImageView is added below the currently selected text field, and below is another MyTextView. This way you can edit the text before and after the image.
Separately, the case is processed when the user, being in the zero position of the text field, presses Backspace - this removes the image, and the two text fields (before and after the image) are glued together into one.
')
To get user-entered text, use the method:
NSString *text = textView.text;

* This source code was highlighted with Source Code Highlighter .

Images in the text are replaced with strings of the form [img1], [img2] ... where the number is (image number + 1) in the array, which can be obtained by
NSArray *images = [textView getImages];

* This source code was highlighted with Source Code Highlighter .


When editing an article, an inverse operation is needed - inserting text with pictures into a component for further editing.
This part will need to "finish" for your needs. In my case, all the image tags were in the form <img src = "/ images / ..." width = "300">, so I made it simple - replacing all such tags with [["image url"]] and implemented the method
[textView setText:parsedText baseUrl:[NSURL URLWithString: @"http://www.site.ru/" ]];

* This source code was highlighted with Source Code Highlighter .


To use the component, it is enough to copy 4 files (located in the UITextViewWithImages group in the example) into your project, in the Interface Builder, add the UIScrollView to the view and change the “Class” to “UITextViewWithImages” in the Identity Inspector

In the example, the basic functionality is implemented, from the shortcomings I can note the impossibility to insert the image "inside" the text field between the already entered lines

Actually the link to the source code example

Source: https://habr.com/ru/post/75516/


All Articles