*准确*计算可可中的文本高度(适用于Mac,不适用于iOS) [英] *Accurately* calculating text height in Cocoa (for Mac, not iOS)

查看:102
本文介绍了*准确*计算可可中的文本高度(适用于Mac,不适用于iOS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于给定的固定宽度,如何计算特定标签(NSTextField)中字符串的高度?

How can I calculate the height of a string within a particular label (NSTextField), for some given fixed width?

我用Google搜索了各种方法,并尝试了苹果公司的这种方法.它的工作原理是,高度对于较短的字符串来说太短了一行.因此,目前的方法似乎存在一些误差.

I Googled up various methods and tried this method from Apple. It works, except that the height becomes one line too short for longer strings. Thus, there appear to be some inaccuracies in the present methods.

我在Google上搜索过的其他一些代码也遇到了同样的问题.

I also had the same issue with some other code I Googled up.

这里的某人是否有任何准确的代码来查找文本高度(给定的特定宽度)?

Does someone here have any accurate code for finding text height (given a particular width)?

推荐答案

我使用了

I solved the problem using the NS(Attributed)String+Geometrics category provided at http://www.sheepsystems.com/sourceCode/sourceStringGeometrics.html Within the header file of that category is a good explanation of how these things work. Specifically, they mention that one should use NSTextView instead of NSTextField because it's virtually impossible to get an accurate height for the latter.

因此,我将NSTextField替换为NSTextView.首先,使用以下代码使NSTextView看起来像我的NSTextField:

Thus, I replaced my NSTextField with NSTextView. First, I made my NSTextView look like my NSTextField with this code:

[textView setEditable:YES];
[textView insertText:someString];
[textView setFont:[NSFont fontWithName:@"Lucida Grande"
   size:11] range:NSMakeRange(0,[someString length])];
[textView setEditable:NO];
[textView setSelectable:NO];

然后我得到了这段代码的高度:

Then I got the height with this code:

NSDictionary *attributes
  = [NSDictionary dictionaryWithObjectsAndKeys:
     [textView font],NSFontAttributeName,nil];
NSAttributedString *attributedString
  = [[NSAttributedString alloc] initWithString:
     [textView string] attributes:attributes];
CGFloat height = [attributedString heightForWidth:
                 [textView frame].size.width];

对于NSTextView来说,高度确实是准确的.

The height does indeed turn out to be accurate for NSTextView.

我可能省略了一些小细节,但是您知道了.我希望这对外面的人有帮助.

I may have omitted some minor details, but you get the picture. I hope this helps someone out there.

这篇关于*准确*计算可可中的文本高度(适用于Mac,不适用于iOS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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