[IOS Development] nsstring-Calculating the width and height of text

Source: Internet
Author: User

In the actual code application, we often need to calculate the width and height of a particular text. Then, depending on the length and width values, the container is dynamically set (for example:UILabel) to accommodate the length and width of the
If: We have the following paragraph of text.

uifont *thefont = [uifontsystemfontofsize:];

NSString *strtext = @ " This is a long string, we will calculate the actual required width and height according to the required font size! " ;


1. Calculate the width of the text
Nsmutabledictionary *dic = [nsmutabledictionary dictionarywithobject:[uifont systemfontofsize:14] ForKey: Nsfontattributename]; Cgsize size = [StrText boundingrectwithsize:cgsizemake (maxfloat, 0.0) options:nsstringdrawinguseslinefragmentorigin Attributes:dic context:nil].size;  

2. Calculate the height of the text

In this way, the size of the container can be controlled by using the Boundingrectwithsize: method to obtain the length and width.
AboutNslinebreakmodeEnumeration type, as shown below, has been made very clear, will not repeat.

typedef Ns_enum (Nsinteger, Nslinebreakmode) {

nslinebreakbywordwrappin g =0,

nslinebreakbycharwrappinG,

nslinebreakbyclipping,

nslinebreakbytruncatinghead,

nslinebreakbytruncatingtail,

nslinebreakbytruncatingmiddle

}Ns_enum_available_ios(6_0);

[IOS Development] nsstring-Calculating the width and height of text

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.