简体   繁体   中英

Adjust Label based on text size in Xamarin IOS

Auto Adjust UILabel size 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 the sample text:

UITextView displays a region that can contain multiple lines of When a user taps a text view, a keyboard appears; when a user taps Return in the keyboard, the keyboard disappears and the text view can handle the input in an application-specific way. You can specify attributes, such as font, color, and alignment, that apply to all text in a text view.

在此输入图像描述

The above text I am using for example. It need to adjust automatically for display the content.

Resolved with below 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);

在此输入图像描述

Here is the code snippet that I use for resizing the label height according to its contents

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;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM