对于给定的固定宽度,如何计算特定标签(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)?
推荐答案我使用了 www.sheepsystems/sourceCode/sourceStringGeometrics.html 在该类别的头文件中,可以很好地解释这些工作原理.具体来说,他们提到应该使用NSTextView而不是NSTextField,因为要获得后者的准确高度实际上是不可能的.
I solved the problem using the NS(Attributed)String+Geometrics category provided at www.sheepsystems/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)
发布评论