获取 NSString 高度
我有一个 NSString,我想知道它的高度以创建合适的 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。 如果我使用这个字符串
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,这是不可能的)...我做错了什么?
ADD:
size.width;
工作正常...所以就像 lineBreakMode 不正确一样...但确实如此,不是吗?
I have an NSString, and I want to know its height to create an appropriate UILabel.
Doing this
NSString *string = @"this is an example";
CGSize size = [string sizeWithFont:[UIFont systemFontOfSize:10.0f]
forWidth:353.0
lineBreakMode:UILineBreakModeWordWrap];
float height = size.height;
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 ";
height is always 13.0 (and with 353 as width, that's impossible)... what am I doing wrong?
ADD:
size.width;
works fine... so it's like if the lineBreakMode is not correct... but it is, isn't it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您所做的事情无法按预期工作的原因是因为
is 用于“计算单行文本的指标”,而
is 用于“计算多行文本的指标”。来自 文档:
尝试使用
-sizeWithFont:constrainedToSize:lineBreakMode:
代替,例如,这是我通常所做的:The reason what you're doing doesn't work as you would expect is because
is for "Computing Metrics for a Single Line of Text" whereas
is for "Computing Metrics for Multiple Lines of Text". From the documentation:
Try using
-sizeWithFont:constrainedToSize:lineBreakMode:
instead, e.g. this is what I usually do:根据 文档
您应该使用 -[NSString sizeWithFont:constrainedToSize:lineBreakMode:] ,它具有类似的行为,但您可以使用 CGFLOAT_MAX 作为传入尺寸的高度。
According to the Documentation
You should to use -[NSString sizeWithFont:constrainedToSize:lineBreakMode:] which has similar behavior but you can uuse CGFLOAT_MAX as the height in the size passed in.