IPhone: Dynamically Retrieve the height and width of uilabel

Source: Internet
Author: User

When using uilabel to store strings, you often need to obtain the long and wide data of the label. This article lists some common calculation methods.

1. Get the width and get the length required when a single line of string is displayed

Cgsize titlesize = [astring sizewithfont: font constrainedtosize: cgsizemake (maxfloat, 30)];

Note: If you want the width, the width of the size should be set to maxfloat.

 

2. Get the height. Get the actual height of the string within the specified size (if the width exceeds the label width, wrap the line.

Cgsize titlesize = [astring sizewithfont: font constrainedtosize: cgsizemake (Label. Frame. Size. Width, maxfloat) linebreakmode: uilinebreakmodewordwrap];

Note: If you want to get the height, set the size height to maxfloat.

 

3. in actual programming, it is sometimes necessary to calculate the position of the last character of a text segment, and add an image or other controls (such as the info icon) after it ), the following code calculates the position of the last character in the label.

Cgsize SZ = [label. Text sizewithfont: Label. Font constrainedtosize: cgsizemake (maxfloat, 40)];

Cgsize linessz = [label. Text sizewithfont: Label. Font constrainedtosize: cgsizemake (Label. Frame. Size. Width, maxfloat) linebreakmode: uilinebreakmodewordwrap];

If (SZ. width <= linessz. width) // determine whether to fold

{

Lastpoint = cgpointmake (Label. Frame. Origin. x + Sz. Width, label. Frame. Origin. y );

}

Else

{

Lastpoint = cgpointmake (Label. Frame. Origin. x + (INT) SZ. Width % (INT) linessz. Width, linessz. Height-Sz. Height );

}

IPhone: Dynamically Retrieve the height and width of uilabel

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.