Code:
-(void) viewdidload {[Super viewdidload]; Additional setup after loading the view, typically from a nib. Gets the width of the string NSLog (@ "Get the width of the string:%f", [Self widthforstring:@ "I love you!" I love you! I love you! I love you! I love you! I love you! I love you! I love you! "fontsize:10.0 andheight:10.0]); Gets the height of the string NSLog (@ "Get the width of the string:%f", [Self heightforstring:@ "I love you!" I love you! I love you! I love you! I love you! I love you! I love you! I love you! "fontsize:10.0 andwidth:10.0]); #pragma-mark-functions//Gets the width of the string-(float) widthforstring: (NSString *) value fontSize: (float) fontSize andheight: ( float) height{cgsize sizetofit = [value Sizewithfont:[uifont systemfontofsize:fontsize] Constrainedtosize:cgsizemake ( Cgfloat_max, height) linebreakmode:nslinebreakbywordwrapping];//here the line-break type (Linebreakmode) can be set according to your own situation return Sizetofit.width;} Get the height of the string-(float) heightforstring: (NSString *) value fontSize: (float) fontSize andwidth: (float) width{cgsize SizeToFit = [value Sizewithfont:[uifont systemfontofsize:fontsize] constrainedtosize:cgsizemake (width, CGFLOAT_MAX) Linebreakmode:nslinebreakbycharwrapping];//the line-break type here (Linebreakmode) can be set according to their actual situation, return sizetofit.height;}
Output:
2015-03-11 15:37:05.375 gets the width of the string [4774:193097] Gets the width of the string : 320.000000
2015-03-11 15:37:05.376 gets the width of the string [4774:193097] Gets the width of the string : 381.760010
Get the width and height of a string