10

Truncate the label text makes it one line. App shows description, it needs to be displayed in 2-3 lines but Xamarin "LineBreakMode=TailTruncation" truncates it and restricts it to one line. Is there any way to truncate label text and show in multi-lines. If text doesn't fit into n number of lines, then it should be truncated.

<Label LineBreakMode="TailTruncation" FontSize = "20" Text="Multi line Text" />

Thanks.

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53
  • SO is a Q&A site. To get a good answer, you should try to ask a good Question first. What you're posted is a list of requirements, not a question. – Jason Jun 23 '16 at 18:16
  • It's limitation of xamarin forms as native android supports multi-line truncation. In native android we can use maxLines. If you can't answer the question, that doesn't mean it's not a question. – PEHLAJ Jun 24 '16 at 04:16

3 Answers3

13

Since Xamarin.Forms 3.3 a new property was introduced for this feature. It's called MaxLines.

Here is an example in C#:

var yourLabel = new Label
{
    LineBreakMode = LineBreakMode.TailTruncation,
    Text = "Your text",
    MaxLines = 2
};

Here is an example in XAML:

<Label
    LineBreakMode="TailTruncation"
    Text="Your text"
    MaxLines="2" />

See https://learn.microsoft.com/de-de/dotnet/api/xamarin.forms.label.maxlines?view=xamarin-forms for more information.

jfmg
  • 2,626
  • 1
  • 24
  • 32
3

I have implemented custom renderer to handle this.

http://depblog.weblogs.us/2016/06/27/xamarin-forms-multi-line-label-custom-renderer-gotcha/

//Droid
public class MultiLineLabelRenderer : LabelRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs e)
    {
        base.OnElementChanged(e);

        if (Control != null)
        {
            Control.LayoutChange += (s, args) =>
            {
                Control.Ellipsize = TextUtils.TruncateAt.End;
                Control.SetMaxLines(2);
            }
        };
    }
}
PEHLAJ
  • 9,980
  • 9
  • 41
  • 53
  • Hi @user12345, does this always work for you? I've implemented the same renderer, but it doesn't longer work after having updated Xamarin.Forms on my project. I describe this [here](https://stackoverflow.com/questions/46042386/xamarin-forms-the-multilinelabel-doesnt-longer-work-on-android) – Gold.strike Sep 04 '17 at 18:29
1

Try with custom label by using UILineBreakMode in iOS:

//iOS
public class CustomMultiLineLabelRenderer : LabelRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
         base.OnElementChanged(e);

         MultiLineLabel multiLineLabel = (MultiLineLabel)Element;

         if (multiLineLabel != null && multiLineLabel.Lines != -1)
         {
              Control.Lines = multiLineLabel.Lines;
              Control.LineBreakMode = UIKit.UILineBreakMode.TailTruncation;
         }
    }
}
AmyNguyen
  • 437
  • 6
  • 10