Label.Font在自定义渲染器中的版本1.3.0错误已过时

时间:2017-10-28 08:27:20

标签: xamarin xamarin.forms

我正在使用自定义渲染器,它允许我证明标签的合理性并添加内部跨度。以下是渲染器的代码:

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

        //if we have a new forms element, update text
        if (e.NewElement != null)
            UpdateTextOnControl();
    }

    protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);

        //if there is change in formatted-text, trigger update to redraw control
        if (e.PropertyName == nameof(Label.FormattedText))
        {
            UpdateTextOnControl();
        }
    }

    void UpdateTextOnControl()
    {
        if (Control == null)
            return;

        //define paragraph-style
        var style = new NSMutableParagraphStyle()
        {
            Alignment = UITextAlignment.Justified,
            FirstLineHeadIndent = 0.001f,

        };

        //define frame to ensure justify alignment is applied
        Control.Frame = new RectangleF(0, 0, (float)Element.Width, (float)Element.Height);
        Control.Lines = 0;

        if (Element.FormattedText.ToAttributed(Element.Font, Element.TextColor) is NSMutableAttributedString attrText)
        {
            var fullRange = new NSRange(0, attrText.Length);
            attrText.AddAttribute(UIStringAttributeKey.ParagraphStyle, style, fullRange);
            Control.AttributedText = attrText;
        }
    }

代码工作正常但在IDE中它向我显示了对此行的警告:

if (Element.FormattedText.ToAttributed(Element.Font, Element.TextColor) is NSMutableAttributedString attrText)

警告声明:

  

Label.Font从版本1.3.0开始已过时

有没有人有任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

第一个选项用于禁用警告:

#pragma warning disable 0618 //retaining legacy call to obsolete code
    if (Element.FormattedText.ToAttributed(font, Element.TextColor) is NSMutableAttributedString attrText)
#pragma warning restore 0618

或者,在此调用中手动创建Font对象作为默认值:

void UpdateTextOnControl()
{
    .....
    .....

    var fontSize = Element.FontSize;
    var fontAttributes = Element.FontAttributes;
    var fontFamily = Element.FontFamily;

    Font font;
    if (fontFamily != null)
        font = Font.OfSize(fontFamily, fontSize).WithAttributes(fontAttributes);
    else
        font = Font.SystemFontOfSize(fontSize, fontAttributes);

    if (Element.FormattedText.ToAttributed(font, Element.TextColor) is NSMutableAttributedString attrText)
    {
        var fullRange = new NSRange(0, attrText.Length);
        attrText.AddAttribute(UIStringAttributeKey.ParagraphStyle, style, fullRange);
        Control.AttributedText = attrText;
    }
}