Vertically aligning text in an NSTextField using Swift

Richard Burton picture Richard Burton · Dec 20, 2015 · Viewed 9.4k times · Source

I have been reading through the various options on how to set the vertical alignment on an NSTextField. I want the text to be displayed in the center and to do it programatically in Swift. Here are the things I have looked so far:

One thing I have tried in Swift is to set the following property:

textField.usesSingleLineMode = true

Any tips on the best way to vertically center text would be much appreciated!

Answer

Andreas Utzinger picture Andreas Utzinger · Dec 20, 2015

This is very hard to do, as Apple makes this very difficult. I achieved it by subclassing NSTextFieldCell and overriding the drawingRectForBounds: method like so:

override func drawingRectForBounds(theRect: NSRect) -> NSRect {
    let newRect = NSRect(x: 0, y: (theRect.size.height - 22) / 2, width: theRect.size.width, height: 22)
    return super.drawingRectForBounds(newRect)
}

This is just my way to do it, I'm sure there are better ways, which I don't know (yet). And this only works for the standard font size in TextFields (which gives a text height of 22). That's why I hardcoded that. Haven't figured out yet, how to get the height in the cell if you change the font.

Result:

enter image description here