cocoanstableviewnstableviewcell

vertically aligning text in NSTableView row


I have a small problem with NSTableView. When I am increasing height of a row in table, the text in it is aligned at top of row but I want to align it vertically centered!

Can anyone suggest me any way to do it ??

Thanks,

Miraaj


Solution

  • This is a simple code solution that shows a subclass you can use to middle align a TextFieldCell.

    the header

    #import <Cocoa/Cocoa.h>
    
    
    @interface MiddleAlignedTextFieldCell : NSTextFieldCell {
    
    }
    
    @end
    

    the code

    @implementation MiddleAlignedTextFieldCell
    
    - (NSRect)titleRectForBounds:(NSRect)theRect {
        NSRect titleFrame = [super titleRectForBounds:theRect];
        NSSize titleSize = [[self attributedStringValue] size];
        titleFrame.origin.y = theRect.origin.y - .5 + (theRect.size.height - titleSize.height) / 2.0;
        return titleFrame;
    }
    
    - (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
        NSRect titleRect = [self titleRectForBounds:cellFrame];
        [[self attributedStringValue] drawInRect:titleRect];
    }
    
    @end
    

    This blog entry shows an alternative solution that also works well.