标签:
代码:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //获取字符串的宽度 NSLog(@"获得字符串的宽度:%f",[self widthForString:@"我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!" fontSize:10.0 andHeight:10.0]); //获取字符串的高度 NSLog(@"获得字符串的宽度:%f",[self heightForString:@"我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!" fontSize:10.0 andWidth:10.0]); } #pragma -mark -functions //获取字符串的宽度 -(float) widthForString:(NSString *)value fontSize:(float)fontSize andHeight:(float)height { CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(CGFLOAT_MAX, height) lineBreakMode:NSLineBreakByWordWrapping];//此处的换行类型(lineBreakMode)可根据自己的实际情况进行设置 return sizeToFit.width; } //获得字符串的高度 -(float) heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width { CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(width, CGFLOAT_MAX) lineBreakMode:NSLineBreakByCharWrapping];//此处的换行类型(lineBreakMode)可根据自己的实际情况进行设置 return sizeToFit.height; }
输出:
2015-03-11 15:37:05.375 获取字符串的宽度[4774:193097] 获得字符串的宽度:320.000000
2015-03-11 15:37:05.376 获取字符串的宽度[4774:193097] 获得字符串的宽度:381.760010
标签:
原文地址:http://www.cnblogs.com/yang-guang-girl/p/4330084.html