Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zpasternack/b8ae67901206bc6f80c9b0c65df8a8a8 to your computer and use it in GitHub Desktop.
Save zpasternack/b8ae67901206bc6f80c9b0c65df8a8a8 to your computer and use it in GitHub Desktop.
Swift port of NSTextFieldCell subclass to vertically align text. Original code here: http://stackoverflow.com/questions/1235219/is-there-a-right-way-to-have-nstextfieldcell-draw-vertically-centered-text
// Makes the text in an NSTextFieldCell vertically centered. Works with single line, non-editable cells.
// Maybe doesn't work with others.
// Stolen from this stackoverflow question:
// http://stackoverflow.com/questions/1235219/is-there-a-right-way-to-have-nstextfieldcell-draw-vertically-centered-text
import Cocoa
class VerticallyCenteredTextFieldCell: NSTextFieldCell {
override func titleRect(forBounds rect: NSRect) -> NSRect {
var titleFrame = super.titleRect(forBounds: rect)
let titleSize = self.attributedStringValue.size()
titleFrame.origin.y = rect.origin.y + (rect.size.height - titleSize.height) / 2.0
return titleFrame
}
override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) {
let titleRect = self.titleRect(forBounds: cellFrame)
self.attributedStringValue.draw(in: titleRect)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment