Hyperlink label in Xamarin.Forms

Many a times we required a hyperlink label in mobile application. For example, you need to show "privacy or Terms and condition" as hyper link and clicking on it should open that link in browser. Unfortunately Xamarin.Forms does not have such in-built control. But it can be achieve using the powerful features called Custom Renderer. I will going to show on how to create a Hyperlink label in this post.

This article assumes, that you know about Xamarin.Forms and have a basic understandings of Custom renders. if not familiar with this, i would suggest read through this. read through this.

Lets dive into code now.

So first create a class called "HyperlinkLabel" which should be inheriting from Xamarin.Form's "Label" control.

public class HyperlinkLabel : Label
{
   public HyperlinkLabel()
   {
   }
}

Label" control.

The definition of class is very simple. It inherited from Label control.

Droid :
Now go to your Android project and create a new class called "HyperlinkLabelRenderer" like below;

using 
MySampleNameSpace.Droid;
using Android.Text.Util;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

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

            Linkify.AddLinks(Control, MatchOptions.All);

        }
    }
}


iOS :

using 
MySampleNamespace.iOS;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(HyperlinkLabel), typeof(HyperlinkLabelRenderer))]
namespace MySampleNamespace.iOS
{
    public class HyperlinkLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            Control.UserInteractionEnabled = true;

            Control.TextColor = UIColor.Blue;

            var gesture = new UITapGestureRecognizer();

            gesture.AddTarget(() =>
            {
                var url = new NSUrl("https://" + Control.Text);

                if (UIApplication.SharedApplication.CanOpenUrl(url))
                    UIApplication.SharedApplication.OpenUrl(url);
            });

            Control.AddGestureRecognizer(gesture);
        }
    }
}



Comments

Popular posts from this blog

Fetching Address book AKA Contact information from Device using Xamarin.Forms

Partial view and AJAX Form with MVC3 Razor