获取NSString高度

我有一个NSString,我想知道它的高度来创build一个合适的UILabel。

这样做

NSString *string = @"this is an example"; CGSize size = [string sizeWithFont:[UIFont systemFontOfSize:10.0f] forWidth:353.0 lineBreakMode:UILineBreakModeWordWrap]; float height = size.height; 

身高现在是13.0。 如果我使用这个string

 NSString *string = @"this is an example this is an example this is an example this is an example this is an example this is an example this is an example this is an example this is an example this is an example this is an example this is an example this is an example this is an example this is an example this is an example "; 

身高总是13.0(宽度353,这是不可能的)…我做错了什么?

加:

 size.width; 

工作正常…所以这就像是如果lineBreakMode是不正确的…但是,是不是?

你所做的原因并不像你期望的那样是因为

 – sizeWithFont:forWidth:lineBreakMode: 

是为“计算单行文本的度量”,而

 -sizeWithFont:constrainedToSize:lineBreakMode: 

是“为多行文本计算度量标准”。 从文档 :

计算单行文本的度量

 – sizeWithFont: – sizeWithFont:forWidth:lineBreakMode: – sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode: 

计算多行文本的度量

 – sizeWithFont:constrainedToSize: – sizeWithFont:constrainedToSize:lineBreakMode: 

尝试使用-sizeWithFont:constrainedToSize:lineBreakMode:相反,例如,这是我通常做的:

 CGSize maximumLabelSize = CGSizeMake(353,9999); CGSize expectedLabelSize = [string sizeWithFont:label.font constrainedToSize:maximumLabelSize lineBreakMode:label.lineBreakMode]; CGRect newFrame = label.frame; newFrame.size.height = expectedLabelSize.height; label.frame = newFrame; 

根据文件

此方法返回约束为指定宽度的string的宽度和高度。 虽然它计算将出现换行符的位置,但此方法实际上不会将文本换行添加到其他行中。 如果string的大小超过了给定的宽度,则此方法使用指定的换行符模式截断文本(仅用于布局目的),直到符合最大宽度; 然后它返回所得到的截断string的大小

你应该使用 – [NSString sizeWithFont:constrainedToSize:lineBreakMode:]它有类似的行为,但你可以使用CGFLOAT_MAX作为传入的大小的高度。