NSString * myText = [NSString stringWithString:@"some text"];
//获取到文本大大小
CGFloat constrainedSize = 265.0f; //其他大小也行
UIFont * myFont = [UIFont fontWithName:@"Arial" size:19]; // UILabel使用的字体
CGSize textSize = [myText sizeWithFont: myFont
constrainedToSize:CGSizeMake(constrainedSize, CGFLOAT_MAX)
lineBreakMode:UILineBreakModeWordWrap];
textSize.width
textSize.height
即为UILable的宽和高,
CGRect labelFrame = CGRectMake (0, 0, textSize.width, textSize.height);
UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
即可用到
工整一些做法:
[cpp]
//计算文本所占高度 //2个参数:宽度和文本内容 -(CGFloat)calculateTextHeight:(CGFloat)widthInput Content:(NSString *)strContent{ CGSize constraint = CGSizeMake(widthInput, 20000.0f); CGSize size = [strContent sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap]; CGFloat height = MAX(size.height, 44.0f); return height; } //计算 宽度 -(CGFloat)calculateTextWidth:(NSString *)strContent{ // CGSize constraint = CGSizeMake(heightInput, heightInput); CGFloat constrainedSize = 26500.0f; //其他大小也行 CGSize size = [strContent sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:CGSizeMake(constrainedSize, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap]; // CGFloat height = MAX(size.height, 44.0f); return size.width; }