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