NSTextField vertical sizeToFit

  • Any way to take an NSTextField containing some amount of text, and resize it
    vertically so all the text fits within the frame? The sizeToFit message
    seems to do this, except on the horizontal axis.
    Thank you!
  • On 2008 Apr, 13, at 1:38, Jeff wrote:

    > Any way to take an NSTextField containing some amount of text, and
    > resize it
    > vertically so all the text fits within the frame? The sizeToFit
    > message
    > seems to do this, except on the horizontal axis.

    If you mean one line of text, there was [NSFont
    defaultLineHeightForFont] but that's depracated in 10.4 and you're
    supposed to use a layout manager (NSLayoutManager).

    If you mean multiple lines of text, you must calculate it using a
    layout manager.  But I could never find a typesetter behavior which
    gave a reliably accurate answer for an NSTextField.  The closest is
    NSTypesetterBehavior_10_2_WithCompatibility.  It seems to me that
    Apple discourages multi-line NSTextFields.  (You can't make one in
    Interface Builder).  My advice: If it's more than one line, use
    NSTextView instead.  A few months ago I put together a demo which
    explains these issues.  You might want to run it, read the comments at
    the top of NS(Attributed)String+Geometrics.h, and/or check out the
    references.

    http://sheepsystems.com/sourceCode/sourceStringGeometrics.html

    Let me know if I made any conceptual errors in that thing.
  • On Apr 13, 2008, at 4:38 AM, Jeff wrote:
    > Any way to take an NSTextField containing some amount of text, and
    > resize it
    > vertically so all the text fits within the frame? The sizeToFit
    > message
    > seems to do this, except on the horizontal axis.
    > Thank you!

    It's a little easier to do this with an NSTextView:

    NSRect frame = NSMakeRect(0, 0, someWidth, MAXFLOAT);
    NSTextView *tv = [[NSTextView alloc] initWithFrame:frame];
    [[tv textStorage] setAttributedString:someAttributedString];
    [tv setHorizontallyResizable:NO];
    [tv sizeToFit];

    You can do a similar process with an NSTextField, but you have to set
    the NSParagraphStyle to word wrap, and I find it easier to just
    configure an NSTextView. If you need an NSTextField, I can walk
    through that.

    -Rob

    --
    Rob Napier -- Software and Security Consulting -- http://robnapier.net
previous month april 2008 next month
MTWTFSS
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30        
Go to today
MindNode
MindNode offered a free license !