如何垂直居中UITextField文本?

Joe*_*oey 143 alignment uitextfield ios

我只是实例化一个UITextField并注意到文本不是垂直居中的.相反,它与我的按钮顶部齐平,我觉得有点奇怪,因为我希望默认值垂直居中.如何将其垂直居中,或者是否存在我缺少的默认设置?

Rog*_*ger 367

textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
Run Code Online (Sandbox Code Playgroud)

迅速使用:

textField.contentVerticalAlignment = UIControlContentVerticalAlignment.center
Run Code Online (Sandbox Code Playgroud)

  • 在Swift 3.0中,这是使用枚举的推荐方法:`textField.contentVerticalAlignment = .center` (2认同)

小智 8

这可能有几个复杂的因素,有些人在之前的答案中提到:

  • 你想要对齐的东西(只是数字,只是字母,只是大写字母或混合)
  • 占位符
  • 清除按钮

什么你要对齐是重要的,因为这点在字体应垂直居中,由于行高,伸,伸等
垂直字体特征http://cdn.ilovetypography.com/img/vert-metrics/gxNh -minion.png
(图片感谢http://ilovetypography.com/2009/01/14/inconspicuous-vertical-metrics/)

例如,当您处理数字时,标准中心对齐看起来不太合适.比较下面两个中的差异,它们使用相同的对齐方式(在下面的代码中),其中一个看起来正确,另一个看起来略微偏离:

混合字母不太对劲:

不看中心的字母

但看起来是正确的,如果它只是数字

数字看起来居中

所以,不幸的是,它可能需要一些试验和错误以及手动调整,以使其看起来在视觉上正确.

我将下面的代码放在UITextField的子类中.它调用超类方法,因为它考虑了存在的清除按钮.

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)
}
Run Code Online (Sandbox Code Playgroud)


Kum*_* KL 5

在情节提要中:在控制之下->根据需要更改垂直和水平对齐方式。

在此处输入图片说明