How do I vertically center UITextField Text?

textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

In swift use:

textField.contentVerticalAlignment = UIControlContentVerticalAlignment.center

This has potentially got several complicating factors, some alluded to in previous answers:

  • What you're trying to align (just numbers, just letters, just uppercase letters or a mix)
  • Placeholders
  • Clear button

What you're trying to align is important because of which point in the font should be vertically centered due to line height, ascenders, descenders etc.
vertical font characteristics
(source: ilovetypography.com)

(Image thanks to http://ilovetypography.com/2009/01/14/inconspicuous-vertical-metrics/ )

When you're dealing with just numbers for example, the standard center alignment won't look quite right. Compare the difference in the two below, which use the same alignment (in the code below), one of which looks correct and the other which looks slightly off:

Not quite right with a mix of letters:

letters not looking centered

but looks right if it's just numbers

numbers looking centered

So, unfortunately, it may need a bit of trial and error and manual adjustment to get it looking visually correct.

I placed the below code in a subclass of UITextField. It calls superclass methods as this takes into account the clear button being present.

override func awakeFromNib() {
    contentVerticalAlignment = UIControlContentVerticalAlignment.Center
}

override func textRectForBounds(bounds: CGRect) -> CGRect {
    let boundsWithClear = super.textRectForBounds(bounds)
    let delta = CGFloat(1)
    return CGRect(x: boundsWithClear.minX, y: delta, width: boundsWithClear.width, height: boundsWithClear.height - delta/2)
}

override func editingRectForBounds(bounds: CGRect) -> CGRect {
    let boundsWithClear = super.editingRectForBounds(bounds)
    let delta = CGFloat(1)
    return CGRect(x: boundsWithClear.minX, y: delta, width: boundsWithClear.width, height: boundsWithClear.height - delta/2)
}

override func placeholderRectForBounds(bounds: CGRect) -> CGRect {
    let delta = CGFloat(1)
    return CGRect(x: bounds.minX, y: delta, width: bounds.width, height: bounds.height - delta/2)
}