Display image-containing HTML using UILabel and detect if an image is tapped in your iOS apps

Make your UILabel graphic and tappable

Thanks to Lukas for the great illustration
let label = UILabel()
label.text = "Some Plain Text"

Part I. Display HTML with an Image

Step 1. The Set-up

Step 2. Configure the UILabel

Set up the label

Step 3. Display the HTML Content

let htmlString = "<html><body><h1>This is the title</h1><p>This is the first paragraph.</p><img src=\"https://miro.medium.com/max/9216/1*QzxcfBpKn5oNM09-vxG_Tw.jpeg\" width=\"360\" height=\"240\"><p>This is the second paragraph.</p><p>This is the third paragraph.</p><p>This is the fourth paragraph.</p><p>This is the last paragraph.</p></body></html>"
label.attributedText = htmlString.convertToAttributedFromHTML()
Display of an image-containing HTML string using UILabel

Part II. Image Tap Gesture Detection

Step 1. Make the label responsive to taps

Step 2. Calculate the tapped character index

The extension function to calculate the tap gesture’s location

Step 3. Determine if an image is tapped

The function in response to a tap gesture
Detect the tap gesture

Conclusions

--

--

Work at the nexus of biomedicine, data science & mobile dev. Author of Python How-to by Manning (https://www.manning.com/books/python-how-to).

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yong Cui

Work at the nexus of biomedicine, data science & mobile dev. Author of Python How-to by Manning (https://www.manning.com/books/python-how-to).