Why would you wanna use a WebView when you could use your Label to display HTML mark up text in your Xamarin Forms app? 😉
How it all started?
Well some times back I had to implement a Xamarin Forms Label which can display HTML formatted text…
The problem with Xamarin Forms Label?
Well of course you would tell me to use the FormattedText property built into Xamarin Forms Label. But before you say that do you even know how limited that property is? and you have to break up your string in to pieces and rebuild it with Span blocks, and also there’s only a few text formatting options available. Usually HTML has a ton of text formatting options, which you can even get close to with the default Xamarin Forms Span block customization.
So the default Xamarin Forms Label can not do any help at this case.
Well we all know it’s super easy to parse HTML text to be rendererd in a Label with Android and iOS native implementation. That’s why I had to drill down to native level and come up with a Custom Label that could display HTML markup text. 😀
Without further due, let’s jump into it! 😉
Create the Custom Control…
So as usual let’s create our Custom Label by subclassing Xamarin Forms Label control.
Nothing fancy there… Next are the big stuff!
Xamarin Android implementation…
So here’s the renderer for our HtmlFormattedLabel
So what we basically do here is native Android TextView through the Control property of our renderer and access the SetText() method, and directly use the Android HTML parser to set your HTML Text.
Xamarin iOS implementation…
Next is our iOS renderer for the custom control.
So here what we do is, we access the native iOS UILabel through the Control property and directly set the AttributedText property with our natively parsed HTML string. 😉
Now unlike Android, I wasn’t much familiar with iOS implementation of HTML text parsing, therefore I took some help from this thread for the above implementation How to display html formatted text in a UILabel ?.
Let’s consume this Awesome Label! 😉
Alright time to use the Awesome Label we just created in Xamarin Forms!
So here I’m using our HtmlFormattedLabel control and directly setting a HTML formatted text to its Text property. 😀
Now hit F5 and Run that beautiful code! 😉
There you have it fellas! 😀
Now you may grab this code from my github: Xamarin-Playground/XFHtmlFormattedLabelControl
And pass on to another Developer by sharing it! 😉