Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically aligning text in an NSTextField using Swift

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:

  • http://www.cocoabuilder.com/archive/cocoa/174994-repositioning-an-nstextfieldcell.html
  • https://red-sweater.com/blog/148/what-a-difference-a-cell-makes
  • Vertically Centre Text in NSSecureTextField with subclassing
  • Get NSTextField contents to scale
  • vertically align text in a CATextLayer?

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!

like image 254
Richard Burton Avatar asked Dec 20 '15 08:12

Richard Burton


2 Answers

I have added the NSTextField inside a NSView and centered it.

Another solution was (in an iOS project) to create a UILabel and allow it adjust its size (sizeToFit()) and again embed it inside a UIView.

I personally don't like the calculations in previous answers and the second solution for iOS works for all texts size and row numbers.

like image 127
Darkwonder Avatar answered Nov 11 '22 13:11

Darkwonder


Try this on a playground, it centers the text perfectly, use it on your projects! Hope it helps!

import Cocoa

let cell = NSTableCellView()
cell.frame = NSRect(x: 0, y: 0, width: 100, height: 100)
let tf = NSTextField()
tf.frame = cell.frame
tf.stringValue = "MyTextfield"
tf.alignment = .Center

let stringHeight: CGFloat = tf.attributedStringValue.size().height
let frame = tf.frame
var titleRect:  NSRect = tf.cell!.titleRectForBounds(frame)

titleRect.size.height = stringHeight + ( stringHeight - (tf.font!.ascender + tf.font!.descender ) )
titleRect.origin.y = frame.size.height / 2  - tf.lastBaselineOffsetFromBottom - tf.font!.xHeight / 2
tf.frame = titleRect
cell.addSubview(tf)
like image 33
Rafa Febrer Avatar answered Nov 11 '22 13:11

Rafa Febrer