ios sizeWithFont:constrainedToSize:

来源:互联网 发布:安装oracle linux 编辑:程序博客网 时间:2024/05/19 05:33

   

sizeWithFont:constrainedToSize:

Returns the size of the string if it were rendered and constrained to the specified size.

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
font

The font to use for computing the string size.

size

The maximum acceptable size for the string. This value is used to calculate where line breaks and wrapping would occur.


CGSize sizeForFit=CGSizeMake(400, 1000);

CGSize sizeName = [

@"新年好新年好新年好新年好新年好新年好新年好新年好新年好新年好新年好新年好新年好新年好新年好新年好新年好新年好新年好新年好新年好"

sizeWithFont:fontName

constrainedToSize:sizeForFit

lineBreakMode:NSLineBreakByWordWrapping];

   NSLog(@"%f,%f",sizeName.width,sizeName.height);

打印结果

2013-02-01 18:08:56.541 ShopDetailInformation[5432:c07] 400.000000,60.000000


如果说sizeForFit=CGSizeMake(4000, 1000);

打印结果

2013-02-01 18:25:39.565 ShopDetailInformation[5485:c07] 1008.000000,20.000000


比较一下,我们会发现,它实际是在指定的区域sizeForFit里,来计算字符串的size大小,返回的sizeName为字符串实际所占的大小。

这个sizeForFit有点讲究,你不能设置的太大,要根据实际情况而定