Underline Label in Xamarin.Forms

Hello everyone, in this post i will create a custom render in order of have a UnderlineLabel,

First of all else, we need to create our class which hierarchy from Xamarin.Forms.Label:

using System;
using Xamarin.Forms;

namespace UnderlineLabelXF
{
    public class UnderlineLabel:Label
    {
        public UnderlineLabel()
        {
        }
    }
}


After that, we need to create the renderer in each platform, first we create in iOS:
We create a folder with the name Renderer, inside of it, we add a class in order of make the renderer:

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

[assembly: ExportRenderer(typeof(UnderlineLabel), typeof(UnderlineRenderer))]
namespace UnderlineLabelXF.iOS
{
    public class UnderlineRenderer:LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            if (this.Control != null)
            {
                if (e.NewElement != null)
                {
                    var label = (UnderlineLabel)this.Element;
                    this.Control.AttributedText = new NSAttributedString(label.Text, underlineStyle: NSUnderlineStyle.Single);
                    Control.TextColor = UIColor.Black;
                }
            }

        }
    }
}


in iOS we add an AttributedText in order of have a Underline text.
Now we can look the result:

So, now we need to do almost the same thing in Android, we add a folder with the name Renderer, and inside of it, we add a class to implement the underline text:

using System;
using Android.Graphics;
using UnderlineLabelXF;
using UnderlineLabelXF.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(UnderlineLabel), typeof(UnderlineRenderer))]
namespace UnderlineLabelXF.Droid
{
    public class UnderlineRenderer: LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            if (this.Control != null)
            {
                Control.PaintFlags = PaintFlags.UnderlineText;
                Control.SetTextColor(Android.Graphics.Color.Black);
            }

        }
    }
}
The PaintFlags allow us select the UnderlineText, but also has another options that we can see in other post.

Now we can look the result:



Here is the url for the complete code on Github:



Follow me on Twitter


Comentarios

Entradas populares de este blog

Entry Show/Hide Password on Xamarin.Forms

Xamarin.Forms Frame

Xamarin.Forms Picker