iOS dynamically calculates the label's wide height

Source: Internet
Author: User

1. Calculate the width of the label according to the text

 1  + (cgfloat) widthofstring: (NSString *)  font: (uifont * 2  { 3  nsdictionary * Dict=[nsdictionary Dictionarywithobject:font Forkey:nsfontattributename];  4  cgrect rect=[string  Boundingrectwithsize:cgsizemake (Cgfloat_max, height) options:nsstringdrawingtruncateslastvisibleline| Nsstringdrawingusesfontleading| nsstringdrawinguseslinefragmentorigin attributes:dict Context:nil];  5  return   Rect.size.width;  6 } 
View Code

2. Calculate the height of the label according to the text

2.1 Method One: Sizethatfits

For example: cgsize size = [Toollabel sizethatfits:cgsizemake ([UIScreen mainscreen].bounds.size.width, MAXFLOAT)];

The size.height you get is the label's height.

2.2 Method Two:

+ (CGFloat) heightofstring: (NSString *)string font: (Uifont *) Font width: (cgfloat) width{    CGRect bounds;     * parameterdict=[nsdictionary dictionarywithobject:font forkey:nsfontattributename];    Bounds=[string boundingrectwithsize:cgsizemake (width, cgfloat_max) options: nsstringdrawingtruncateslastvisibleline| Nsstringdrawingusesfontleading| nsstringdrawinguseslinefragmentorigin attributes:parameterdict Context:nil];     return bounds.size.height;}
View Code

iOS dynamically calculates the label's wide height

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.