2 daffodilgirl DaffodilGirl 于 2013.02.16 15:30 提问

使用sizeWithFont:constrainedToSize:lineBreakMode

在IOS6.1SDK中运行下面的代码:

UIFont *font = [UIFont fontWithName:@"Avenir" size:12.0];

NSString *text1 = @"Short Label";
NSString *text2 = @"Long Label Whose Text Will Be Truncated Because It Is Too Long For The View";

CGSize text1Size = [text1 sizeWithFont:font 
                     constrainedToSize:
                            CGSizeMake(self.view.frame.size.width, CGFLOAT_MAX) 
                         lineBreakMode:NSLineBreakByTruncatingTail];
CGSize text2Size = [text2 sizeWithFont:font 
                     constrainedToSize:
                            CGSizeMake(self.view.frame.size.width, CGFLOAT_MAX) 
                         lineBreakMode:NSLineBreakByTruncatingTail];

NSLog(@"Text 1 Size: %f %f", text1Size.width, text1Size.height);
NSLog(@"Text 2 Size: %f %f", text2Size.width, text2Size.height);

日志输出是:

Text 1 Size: 62.000000 17.000000
Text 2 Size: 300.000000 34.000000

为什么高度不一致?两种情况下都是一行text。

1个回答

wangyaninglm
wangyaninglm   Ds   Rxr 2015.01.13 23:45

UIFont *font = [UIFont systemFontOfSize:12];

CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(150.0f, 1000.0f) lineBreakMode:UILineBreakModeCharacterWrap];

获取字符串在指定的size内(宽度超过150,则换行)所需的的实际高度和宽度.
将获取的宽度和高度用于UILabel
UILabel *bubbleText = [[UILabel alloc] initWithFrame:CGRectMake(21.0f, 14.0f, size.width+10, size.height+10)];

bubbleText.backgroundColor = [UIColor clearColor];

bubbleText.font = font;

bubbleText.numberOfLines = 0;

bubbleText.lineBreakMode = UILineBreakModeCharacterWrap;

bubbleText.text = text;

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!