Set text vertical center in NSTextField

Viewed 21772

In a certain height NSTextField , the layout would be like this if text's size is small

enter image description here

the text is flowing to the top ,how to make the text center like this:

enter image description here

6 Answers

Swift version of Erik Wegener's answer (also modified to work with multiple lines too):

class VerticallyCenteredTextFieldCell : NSTextFieldCell {
    override func titleRect(forBounds rect: NSRect) -> NSRect {
        var titleRect = super.titleRect(forBounds: rect)

        let minimumHeight = self.cellSize(forBounds: rect).height
        titleRect.origin.y += (titleRect.height - minimumHeight) / 2
        titleRect.size.height = minimumHeight

        return titleRect
    }

    override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) {
        super.drawInterior(withFrame: titleRect(forBounds: cellFrame), in: controlView)
    }
}

My solution is based to calculate font height using NSLayoutManager. This way allow more performance that calculate height using methods of attributed string.

- (NSRect)titleRectForBounds:(NSRect)theRect {
    NSRect titleFrame = [super titleRectForBounds:theRect];

    CGFloat fontHeight = [[[NSLayoutManager alloc] init] defaultLineHeightForFont:self.font];
    if (fontHeight < titleFrame.size.height) {
        titleFrame.origin.y = theRect.origin.y + (theRect.size.height - fontHeight) * 0.5f;
        titleFrame.size.height = fontHeight;
    }
    return titleFrame;
}

- (void) drawInteriorWithFrame:(NSRect)frame inView:(NSView *)view {
    [super drawInteriorWithFrame:[self titleRectForBounds:frame] inView:view];
}
Related