Codementor Events

Xamarin.Forms: Hyperlink Label

Published Apr 04, 2017

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 be 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: https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/.

Lets dive into code now.
Create a new project of Xamarin.Forms (PCL/Shared).
Once you done creating a project, go to your PCL/Shared prject and create a class called "HyperlinkLabel" which should be inheriting from Xamarin.Form's "Label" control.

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

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

In your page where you want to show HyperLink, use following XAML:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:Controls="clr-namespace:YourNameSpace"
             x:Class="YourNameSpace.YourPageName"
             Title="Hyperlink Label">
  <Grid Padding="10">
     
    <Controls:HyperlinkLabel Text="codementor.com" HorizontalOptions="Center" VerticalOptions="End" />
  </Grid>

</ContentPage>

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

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

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

            Linkify.AddLinks(Control, MatchOptions.All);

        }
    }
}

iOS :
Create class in your iOS project.

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

[assembly:ExportRenderer(typeof(HyperlinkLabel),typeof(HyperlinkLabelRenderer))]
namespace YourNameSpace.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);
        }
    }
}
Discover and read more posts from Sudhir
get started
post commentsBe the first to share your opinion
Даниил Афанасьев
2 years ago

Hello Sudhir, thanks for your code sharing. I need a custom Label with TextType html and clickable links (open link in browser). I have try your code for Android and it is not working((
Maybe you have another solution for that?
(I have already find solution for iOS, need only Android now)

iOS solution:
[assembly: ExportRenderer(typeof(LinksLabel), typeof(HtmlLabelRenderer))]
namespace Project.iOS
{
public class HtmlLabelRenderer : ViewRenderer<Label, UITextView>
{
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);

        var view = (LinksLabel)Element;

        if (view == null) return;

        UITextView textView;

        if (Control == null)
        {
            textView = new UITextView();
            SetNativeControl(textView);
        }
        else if (e.PropertyName == Label.TextProperty.PropertyName)
        {
            if (Element != null && !string.IsNullOrWhiteSpace(Element.Text))
            {
                var attr = new NSAttributedStringDocumentAttributes();
                var nsError = new NSError();
                attr.DocumentType = NSDocumentType.HTML;

                var myHtmlData = NSData.FromString(view.Text, NSStringEncoding.Unicode);
                Control.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);

                Control.ScrollEnabled = false;
                Control.Font = UIFont.SystemFontOfSize(16);
            }
        }
    }
}

}

gadda raju
3 years ago

Hello Sudhir, Thank you for sharing your valuable code. when I implement the code in android it is working fine in IOS I’m facing the issue i.e “Message “Could not initialize an instance of the type ‘Foundation.NSUrl’: the native ‘initWithString:’ method returned nil.\nIt is possible to ignore this condition by setting ObjCRuntime.Class.ThrowOnInitFailure to false.” string”. Im the new to this Xamarin forms please help me out Sudhir. Thanks in advance.

Sudhir
3 years ago

What is the URL that you’re trying to open? does it have any unicode characters?

Show more replies