获取NSString高度 [英] Get the NSString height

查看:109
本文介绍了获取NSString高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an NSString, and I want to know its height to create an appropriate 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。
如果我使用这个字符串

height is now 13.0. If I use this 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,这是不可能的)......我在做什么错误?

height is always 13.0 (and with 353 as width, that's impossible)... what am I doing wrong?

ADD:

size.width;

工作得很好......所以就像lineBreakMode不正确一样......但它是,不是吗?

works fine... so it's like if the lineBreakMode is not correct... but it is, isn't it?

推荐答案

你正在做的事情并不像你期望的那样工作是因为

The reason what you're doing doesn't work as you would expect is because

– sizeWithFont:forWidth:lineBreakMode: 

用于计算单行文本的度量标准,而

is for "Computing Metrics for a Single Line of Text" whereas

-sizeWithFont:constrainedToSize:lineBreakMode:

用于计算多行文本的度量标准。来自文档

is for "Computing Metrics for Multiple Lines of Text". From the documentation:


计算单行文本的度量标准

Computing Metrics for a Single Line of Text

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

计算多行文本的度量标准

Computing Metrics for Multiple Lines of Text

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


尝试使用 -sizeWithFont:constrainedToSize:lineBreakMode:代替,例如这就是我通常做的事情:

Try using -sizeWithFont:constrainedToSize:lineBreakMode: instead, e.g. this is what I usually do:

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;

这篇关于获取NSString高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆