Awesome Xamarin Forms Label with HTML Text Formatting…

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.

Solution?

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.

namespace WhateverYourNamespace
{
    public class HtmlFormattedLabel : Label
    {

    }
}

 

Nothing fancy there… Next are the big stuff!

Xamarin Android implementation…

So here’s the renderer for our HtmlFormattedLabel

[assembly:ExportRenderer(typeof(HtmlFormattedLabel), typeof(HtmlFormattedLabelRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class HtmlFormattedLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            var view = (HtmlFormattedLabel)Element;
            if (view == null) return;
            
            Control.SetText(Html.FromHtml(view.Text.ToString()),TextView.BufferType.Spannable);
        }
    }
}

 

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.

[assembly:ExportRenderer(typeof(HtmlFormattedLabel), typeof(HtmlFormattedLabelRenderer))]
namespace WhateverYourNamespace.iOS
{
    public class HtmlFormattedLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            
            var view = (HtmlFormattedLabel)Element;
            if (view == null) return;

            var attr = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();
            attr.DocumentType = NSDocumentType.HTML;
            
            Control.AttributedText = new NSAttributedString(view.Text, attr, ref nsError);
        }
    }
}

 

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 ?.

KABOOM! EASY!

Let’s consume this Awesome Label! 😉

Alright time to use the Awesome Label we just created in Xamarin Forms!

Content = new StackLayout
{
	VerticalOptions = LayoutOptions.Center,
	Padding = new Thickness(20,0,20,0),
	Spacing = 30,
	Children = {
		new Label {
			HorizontalTextAlignment = TextAlignment.Center,
			TextColor = Color.Black,
			Text = "Welcome to the awesome HTML Formatter Label" +
			"Control by ÇøŋfuzëÐ SøurcëÇødë!"
		},
		new HtmlFormattedLabel()
		{
			FontSize = 14,
			TextColor = Color.Black,
			Text = 
			   "<html><body><Center>" +
			   "<font size='6'>" +
			   "This is a html formatted text," +
			   "so this is <b>bold text</b>... " +
			   "and this is <u>underline text</u>... " +
			   "and this is <strike>strike through text</strike>... " +
			   "and finally this is <i>italic text</i>... " +
			   "<br />" +
			   "Ops this is html line break..." +
			   "<br />" +
			   "And this is <sup>superscripted</sup> html text."+
			   "</font>" +
			   "<Center></body></html>",
		}
	}
}

 

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! 😉

screen-shot-2017-02-05-at-4-08-31-pmnexus-5-lollipop-screenshot-3

There you have it fellas! 😀

Now you may grab this code from my github: Xamarin-Playground/XFHtmlFormattedLabelControl

Enjoy!

And pass on to another Developer by sharing it! 😉

Advertisements

2 thoughts on “Awesome Xamarin Forms Label with HTML Text Formatting…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s