on 05/12/19 19:02, John Stiles at JStiles (AT) blizzard (DOT) com wrote:
I have a regular NSTextView inside an NSScrollView (with an auto-
hiding vertical scroll bar). The contents of the text view are set
via code depending on the outcome of some operations. The scroll view
is set up to grow as my window is resized. So far, everything is
working great.
Now, I'd like to be able to determine how large the NSTextView ought
to be to avoid scrolling. That way, I can set the window to its
"optimal" size before showing it big enough to show the text,
without having a ton of extra white space.
Is there an easy way to do this?
Nope. No easy way. Maybe in Mac S 11. Until then we have this:
which you can find explained in the docs on your hard drive:
ADC Home Reference Library Documentation Cocoa Text & Fonts Text
Layout Programming Guide Calculating Text Height
The above explains how to do it for constant width and variable height,
which is the opposite of what you want, but their function is easily
modified to do either way:
float MeasureStringDrawing(NSString *myString, NSFont *desiredFont, float
desiredWidth, float desiredHeight)
// of desiredHeight or desiredWidth must be set to 0.
// The size of the one set to 0 will be returned.
// of this function is explained in:
// ADC Home Reference Library Documentation Cocoa Text & Fonts >
Text Layout Programming Guide Calculating Text Height
{
BL wantWidth ;
if (desiredWidth == 0)
{
desiredWidth = 1e7 ;
wantWidth = YES ;
}
else if (desiredHeight == 0)
{
desiredHeight = 1e7 ;
wantWidth = N ;
}
else
NSLog(@ "Internal error calling HeightForStringDrawing") ;
NSTextStorage *textStorage = [[[NSTextStorage alloc]
initWithString:myString] autorelease];
NSTextContainer *textContainer = [[[NSTextContainer alloc]
(desiredWidth, desiredHeight)] autorelease];
NSLayoutManager *layoutManager = [[[NSLayoutManager alloc] init]
autorelease];
[textStorage value:desiredFont
range:NSMakeRange(0, [textStorage length])];
[textContainer setLineFragmentPadding:0.0]; // padding usually is not
appropriate for string drawing
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
(void)[layoutManager ]; //
force layout
if (wantWidth)
return [layoutManager
].size.width;
else
return [layoutManager
].size.height;
}
P.S. You may find that you need to add a little margin. I don't know why,
but to guarantee no wrapping I have to add 15 pixels to the returned
measurement. The required margin may depend on your font, size, etc.
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (Cocoa-dev (AT) lists (DOT) apple.com)
Help/Unsubscribe/Update your Subscription:
%40developershed.com
This email sent to bsdarchive (AT) developershed (DOT) com