Returns the width and height of a string.
Code:
-(Void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // obtain the string width NSLog (@ "get string width: % 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]); // obtain the string height NSLog (@" Get the string width: % 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 // obtain the string width-(float) widthForString :( NSString *) value fontSize :( float) fontSize andHeight :( float) height {CGSize sizeToFit = [value sizeWithFont: [UIFont systemFontOfSize: fontSize] constrainedToSize: CGSizeMake (CGFLOAT_MAX, height) lineBreakMode: timeout] // The line feed type (lineBreakMode) can be set to return sizeToFit according to your actual situation. width;} // obtain the string height-(float) heightForString :( NSString *) value fontSize :( float) fontSize andWidth :( float) width {CGSize sizeToFit = [value sizeWithFont: [UIFont systemFontOfSize: fontSize] fill: CGSizeMake (width, CGFLOAT_MAX) lineBreakMode: Fill]; // set the line feed type (lineBreakMode) based on your actual situation. return sizeToFit. height ;}
Output:
2015-03-11 15:37:05. 375Returns the string width.[4774: 193097]Returns the string width.320.000000
2015-03-11 15:37:05. 376Returns the string width.[4774: 193097]Returns the string width.381.760010