更新时间:2023-09-21 15:44:28
但是在更新到最新版本(Xamarin.Forms v.2.4.0.269-pre2)之后,它不再能按预期工作:
But after having updated to the latest version (Xamarin.Forms v.2.4.0.269-pre2), it doesn't longer work as expected:
原因:
我已经检查了Xamarin.Forms v.2.4.0.269-pre2
的源代码.在LabelRenderer
的OnElementChange
事件中,将调用FormsTextView
的SetLineBreakMode
,其中包含以下代码:
I've checked the source codes of Xamarin.Forms v.2.4.0.269-pre2
. In LabelRenderer
's OnElementChange
event, FormsTextView
's SetLineBreakMode
will be called which contains following codes:
public static void SetLineBreakMode(this TextView textView, LineBreakMode lineBreakMode)
{
switch (lineBreakMode)
{
case LineBreakMode.NoWrap:
textView.SetMaxLines(1);
textView.SetSingleLine(true);
textView.Ellipsize = null;
break;
case LineBreakMode.WordWrap:
textView.Ellipsize = null;
textView.SetMaxLines(100);
textView.SetSingleLine(false);
break;
case LineBreakMode.CharacterWrap:
textView.Ellipsize = null;
textView.SetMaxLines(100);
textView.SetSingleLine(false);
break;
case LineBreakMode.HeadTruncation:
textView.SetMaxLines(1);
textView.SetSingleLine(true);
textView.Ellipsize = TextUtils.TruncateAt.Start;
break;
case LineBreakMode.TailTruncation:
textView.SetMaxLines(1);
textView.SetSingleLine(true);
textView.Ellipsize = TextUtils.TruncateAt.End;
break;
case LineBreakMode.MiddleTruncation:
textView.SetMaxLines(1);
textView.SetSingleLine(true);
textView.Ellipsize = TextUtils.TruncateAt.Middle;
break;
}
}
如您所见,如果使用LineBreakMode.TailTruncation
,则会调用textView.SetMaxLines(1);
和textView.SetSingleLine(true);
,这将禁用多行功能.(在2.3.4
textView.SetSingleLine(true);
中不存在).
As you can see, if you use LineBreakMode.TailTruncation
, textView.SetMaxLines(1);
and textView.SetSingleLine(true);
will be called, which disable the multi line function.(In 2.3.4
textView.SetSingleLine(true);
doesn't exist).
解决方案:
要解决此问题,只需在渲染器中添加两行代码:
To fix the problem, you simply need to add two lines of codes in your renderer:
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Label> e)
{
base.OnElementChanged(e);
MultiLineLabel multiLineLabel = (MultiLineLabel)Element;
if (multiLineLabel != null && multiLineLabel.Lines != -1)
{
Control.SetSingleLine(false);
Control.SetMaxLines(multiLineLabel.Lines);
Control.SetLines(multiLineLabel.Lines);
}
}