NSString的sizeWithAttributes:不准确 [英] NSString sizeWithAttributes: Inaccuracy

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

问题描述

我想知道显示在像素在屏幕上一个NSString的宽度。这样我就可以适应了的NSTextField其边界是字符串本身的确切长度。所以我用IB的标签的NSTextField并为那些谁不知道我的意思,我根据标题为标签标签,字体龙力大13px的,不可选,不可编辑,常规尺寸,没有任何背景,到IB其宽度38px宽。

I want to know the width of an NSString displayed on the screen in pixels. So I can fit an NSTextField its bounds to be exactly the length of the string itself. So I used IB's "Label" NSTextField and for those who don't know what I mean, I got a label with title "Label", font "Lucida Grande 13px", not selectable, not editable, regular size, no background and according to IB its width is 38px wide.

如果我想获得它的宽度编程我用

If I want to get its width programatically I use

[@"Label" sizeWithAttributes: [NSDictionary dictionaryWithObject: [NSFont fontWithName: @"Lucida Grande" size: 13] forKey: NSFontAttributeName]].width

哪位能给我33.293457。所以这是约5像素的实际宽度。

Which will give me 33.293457 . So that's about 5 px of the real width..

推荐答案

我相信你都注意到的是控制的框架之间的差异,它的布局框架。见<一href=\"http://stackoverflow.com/questions/914102/whats-the-difference-between-frame-and-layout-in-interface-builders-size-inspec\">Frame VS一个很好的说明布局框架。

I believe what you are noticing is the difference between the frame of the control and it's layout frame. See Frame vs Layout Frame for a good explanation.

您正在做计算宽度正确的事情。对于标签,还有在控制,这就是为什么你看到你的控件的高度没有问题的顶部或底部没有微胖。然而,在左侧和控制权,有一个附加的三个像素。这可以通过在IB Label控件的框架和布局进行验证。

You are doing the right thing in computing the width. For a Label, there is no extra padding at the top or bottom of the control, which is why you saw no problems with the height of your control. However, on the left and right of the control, there are an additional three pixels. This can be verified by looking at the Frame and Layout of a Label control in IB.

所以,你注意到了〜5个像素,实际上正是6.一旦你考虑到这一点填充,你应该没有进一步的麻烦。

So, the ~5 pixels you noticed is actually exactly 6. Once you take into account this padding, you should have no further trouble.

不幸的是,没有API来确定填充是关于各种控件(按钮在每侧有额外的6个像素)。我建议在 http://bugreport.apple.com 提交bug报告 - 苹果并未基地,他们在某种程度上提供了一些什么的API的请求对它们。尽管IB会告诉你,你将需要code这些值自己。如果他们在未来的OS版本改变,你需要更新你的应用程序。

Unfortunately, there is no API to determine what the padding is for various controls (Push Buttons have an additional 6 pixels on each side). I would suggest filing a bug report at http://bugreport.apple.com - Apple does base what APIs they provide in part on the number of requests for them. While IB will tell you, you will need to code those values yourself. If they change in the next OS release, you will need to update your application.

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

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