Multi-line text truncation in Xamarin Forms

Truncate the label in Xamarin forms by add LineBreakMode = TailTruncation is easy, but it truncates it and restricts it to one line. But on a specific label we wanted to show more text to the end user and even than add an ellipsis if needed. So in other words we would love to be able to tell the label control how many lines it should at least try to display.

To get this working in Xamarin forms you’ll need to add a custom renderer. Because the Xamarin forms label control doesn’t have any property available for us to manipulate to accomplish this.

Forms control

In the Xamarin forms PCL, we first add a class called MultiLineBreakLabel.cs – this will be our own custom control.

Android renderer

[assembly: ExportRenderer(typeof(MultiLineBreakLabel), typeof(MultiLineBreakLabelRenderer))]
namespace Xamarin.Forms.Samples.Droid.Renderers
{
public class MultiLineBreakLabelRenderer : LabelRenderer
{
#region -- Overrides --
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if (Control != null)
{
var label = (MultiLineBreakLabel)this.Element;
Control.SetMaxLines(label.MaxLines);
}
}
#endregion
}
}

iOS renderer

[assembly: ExportRenderer(typeof(MultiLineBreakLabel), typeof(MultiLineBreakLabelRenderer))]
namespace Xamarin.Forms.Samples.iOS.Renderers
{
public class MultiLineBreakLabelRenderer : LabelRenderer
{
#region -- Overrides --
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
var label = Element as MultiLineBreakLabel;
if (label == null || Control == null)
{
return;
}
Control.Lines = label.MaxLines;
}
#endregion
}
}

After defining this custom control, we can use it on our XAML page, like so:

<controls:MultiLineBreakLabel
LineBreakMode="TailTruncation"
Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas at vehicula mauris, et accumsan urna. Ut sagittis laoreet enim, suscipit tristique urna rhoncus non."
MaxLines="3" />

The following screenshots show the label on each platform:

screenshot

Repo for LetterSpacingLabel can be found on Github.

Written on May 21, 2017