Is there a way that I can use Spans inside of a label and also have it justified?

前端 未结 1 1065
無奈伤痛
無奈伤痛 2021-01-06 04:24

I am using this code to add some colors to my text inside of a label:


  
     

        
相关标签:
1条回答
  • 2021-01-06 04:43

    You will have to update the renderer to consider FormattedText. For e.g.: try changing renderer logic to following:

    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;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题