Search code examples
xamarinxamarin.iosmvvmcross

MvvmCross iOS UILabel AttributedText with Language converter


I create a custom control for UILabel with custom Kern parameter.

 [Register("CustomLabelView"), DesignTimeVisible(true)]
    public class CustomLabelView : UILabel
    {
        private float _textLetterSpacing;

        public CustomLabelView(IntPtr handle) : base(handle)
        {
        }

        [Export("TextLetterSpacing"), Browsable(true)]
        public float TextLetterSpacing
        {
            get => _textLetterSpacing;
            set
            {
                _textLetterSpacing = value;
                SetNeedsDisplay();
            }
        }

        public CustomLabelView()
        {
            Initialize();
        }

        public override void AwakeFromNib()
        {
            // Called when loaded from xib or storyboard.
            Initialize();
        }

        void Initialize()
        {
            NSRange range = new NSRange(0, Text.Length);
            var attributes = AttributedText.GetCoreTextAttributes(0, out range);
            var attributedTitle = new NSAttributedString(Text, new CTStringAttributes() { KerningAdjustment = TextLetterSpacing, ForegroundColor = TextColor.CGColor, UnderlineStyle = attributes.UnderlineStyle });
            AttributedText = attributedTitle;
            SetNeedsDisplay();
        }
    }

I bind text to this control with language converter

set.Bind(CustomLabelView)
   .For(c => c.Text)
   .To(vm => vm.TextSource)
   .WithConversion("Language", "AgreementText");

and underline property doesn't apply for bound text. Also I tried AttributedText property instead of Text. No any changes.

My LinkerPleaseInclude file contains this lines

public void Include(UILabel label)
{
  label.Text = label.Text + "";
  label.AttributedText = new NSAttributedString(label.AttributedText.ToString() + "");            
}

Any ideas how to sort it out?


Solution

  • I just put Initialize method into Draw for my CustomLabel.

    Here is the solution:

     public override void Draw(CGRect rect)
     {
         Initialize();
         base.Draw(rect);
     }
    
     private void Initialize()
     {
         var attributes = AttributedText.GetCoreTextAttributes(0, out _);
         AttributedText = new NSMutableAttributedString(Text,
                    new CTStringAttributes
                    {
                        KerningAdjustment = TextLetterSpacing, Font = attributes.Font,
                        UnderlineStyle = attributes.UnderlineStyle
                    });
     }