Adjust label based on text size in Xamarin IOS

Automatic sizing of UILabel based on text.

lbl_genericIndicators.Font = UIFont.FromName (KHELVETIC, KFontSize12);
float width = View.Frame.Size.Width-20;
SizeF size = ((NSString)lbl_genericIndicators.Text).StringSize(lbl_genericIndicators.Font,constrainedToSize:new SizeF(width,100),
lineBreakMode:UILineBreakMode.WordWrap);
var labelFrame = lbl_genericIndicators.Frame;
labelFrame.Size = new SizeF(width,size.Height);
lbl_genericIndicators.Frame = new RectangleF (10, 128, size.Width,size.Height);

      

Below is a sample text:

UITextView displays an area that can contain multiple lines. When the user enters a text view, a keyboard appears; when the user drops the keyboard, the keyboard disappears and the text view can handle the input depending on the application. You can specify attributes such as font, color, and alignment that apply to all text in the text view.

enter image description here

The above text I use for example. It should automatically configure itself to display content.

+3


source to share


2 answers


Allowed by code

lbl_genericIndicators.Font = UIFont.FromName (KHELVETIC, KFontSize12);
lbl_genericIndicators.BackgroundColor = UIColor.Red;
lbl_genericIndicators.TextAlignment = UITextAlignment.Justified;
float width = View.Frame.Size.Width-20;
SizeF size=((NSString)lbl_genericIndicators.Text).StringSize(lbl_genericIndicators.Font,constrainedToSize:new SizeF(width,100),lineBreakMode:UILineBreakMode.WordWrap);
var labelFrame = lbl_genericIndicators.Frame;
labelFrame.Size = new SizeF(width,size.Height);
lbl_genericIndicators.Lines = int.Parse((lbl_genericIndicators.Text.Length / 40).ToString()) + 1;
lbl_genericIndicators.Frame = new RectangleF (10, 128, size.Width,size.Height);

      



enter image description here

+3


source


Here is a piece of code that I am using to change the height of the label to fit its content



void ChangeLabelHeigthWithText(UITextView label,float maxHeight = 100f) 
        {
            float width = label.Frame.Width; 
            SizeF size = ((NSString)label.Text).StringSize(label.Font,constrainedToSize:new SizeF(width,maxHeight),
                    lineBreakMode:UILineBreakMode.WordWrap);
            var labelFrame = label.Frame;
            labelFrame.Size = new SizeF(width,size.Height);
            label.Frame = labelFrame;
        }

      

+1


source







All Articles