3

I need to bottom align the text in my NSTextField so that the bottom pixel rows of my text always stays in the same spot when dynamically changing the font size (I use this to do that).

Right now I have this scenario: whenever the font size gets smaller e.g from 55 to 20, the text hangs at the top of the bounds/frame and this is not what I need.

I haven't found anything that lets me align the text at the bottom but I did find this and adjusted it for my custom NSTextFieldCell subclass:

- (NSRect)titleRectForBounds:(NSRect)theRect {
    NSRect titleFrame = [super titleRectForBounds:theRect];
//    NSSize titleSize = [[self attributedStringValue] size];
    titleFrame.origin.y = theRect.origin.y;
    return titleFrame;
}

- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
    NSRect titleRect = [self titleRectForBounds:cellFrame];
    [[self attributedStringValue] drawInRect:titleRect];
}

I also used [myTextField setCell:myTextFieldCell]; so that my NSTextField uses the NSTextFieldCell but nothing has changed. Did I not adjust this correctly or what else am I doing wrong?

Community
  • 1
  • 1
iMaddin
  • 982
  • 1
  • 14
  • 23

1 Answers1

0

You need to adjust the height of the titleRect as it is taller than needed if the font was reduced. So something like this that adjusts the height and shifts the titleRect down by the height difference.

- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
    NSRect titleRect = [super titleRectForBounds:cellFrame];
    NSSize titleSize = [[self attributedStringValue] size];
    CGFloat heightDiff = titleRect.size.height - titleSize.height;
    titleRect = NSMakeRect(titleRect.origin.x, titleRect.origin.y + heightDiff, titleRect.size.width, titleSize.height);
    [[self attributedStringValue] drawInRect:titleRect];
}

You could also do drawAtPoint: instead of drawInRect: to provide exact placement, but if the text is not left justified you would have to calculate the correct x position as well.

InfalibleCoinage
  • 588
  • 13
  • 21