2

I have the body (HTML with images) of a wordpress article obtained via JSON, I'm using a UITextView` to show it and everything works correctly, except that the image that contains the HTML only shows a part.

To format the HTML content, I use the following extension:

extension NSAttributedString {
    convenience init?(html: String) {
        guard let data = html.data(using: String.Encoding.unicode, allowLossyConversion: false) else {
            return nil
        }
        guard let attributedString = try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else {
            return nil
        }
        self.init(attributedString: attributedString)
    }
}

and to show it in the UITextView, I do it like this:

myTextView.attributedText = NSAttributedString(html: htmlString!)

In var htmlString: HTML is stored.

All good, except that when loading the image of the HTML content it does not scale.

This is how the image looks

How could I make the HTML content images show autoscaling?

The html code of the images are similar to:

<img class="alignnone size-full wp-image-9667" src="https://.../wp-content/uploads/2016/02/image.jpg" alt="image" width="612" height="894">

CSS could be added?

  • In case you cannot do it with HTML (nothing say that iOS will translate it correctly, especially since you translate it into NSAttributedString, NSTextAttachment doesn't have that option and it's not linked yet to UI so it doesn't know the size), you'd need to enumerate for `NSAttachmentAttributeName` and resize yourself the image – Larme Mar 24 '18 at 20:42
  • Here is a sample to enumerate : https://stackoverflow.com/questions/44027651/convert-attributed-string-to-simple-tagged-html/44051956#44051956 and for the resize: https://stackoverflow.com/questions/22357171/how-to-resize-an-image-or-done-as-a-nsattributedstring-nstextattachment-or-set – Larme Mar 24 '18 at 20:42
  • Thank you very much for your response, I have been reviewing, but it is an image inside an html, I do not have the name of the image and the extensions for "NSTextAttachment" need the name of the image. – Mercadeo Web Mar 25 '18 at 00:31
  • You don't need the name of the image. Just read there: https://stackoverflow.com/a/46321759/1801544 and instead of appending the image, do `attachment.bounds = calculateRatioAccordingToYourTextView` – Larme Mar 25 '18 at 10:48
  • @MercadeoWeb, even i got same issue have you found solution ? – Arshad Shaik Apr 13 '20 at 05:16

0 Answers0