如何垂直居中 UITextField 文本?
我只是实例化一个 UITextField
并注意到文本没有垂直居中。相反,它与按钮的顶部齐平,我觉得这有点奇怪,因为我希望默认设置将其垂直居中。如何将其垂直居中,或者是否缺少一些默认设置?
I am simply instantiating a UITextField
and noticing that the text doesn't center vertically. Instead, it is flush with the top of my button, which I find kind of odd since I would expect the default to center it vertically. How can I center it vertically, or is there some default setting that I am missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
快速使用时:
In swift use:
这可能会带来几个复杂的因素,其中一些在之前的答案中提到过:
什么尝试对齐很重要,因为由于行高、上升部分、下降部分等原因,字体中的哪个点应该垂直居中。
(来源:ilovetypography.com)
(图片感谢http://ilovetypography.com/2009/ 01/14/inconspicously-vertical-metrics/ )
例如,当您仅处理数字时,标准中心对齐方式看起来不太正确。比较下面两者的差异,它们使用相同的对齐方式(在下面的代码中),其中一个看起来正确,另一个看起来有点不对劲:
混合字母不太正确:
< img src="https://i.sstatic.net/AsFLa.png" alt="字母看起来不居中">
但如果只是数字看起来就正确
因此,不幸的是,它可能需要一些尝试、错误和手动调整才能使其看起来在视觉上正确。
我将以下代码放置在 UITextField 的子类中。它调用超类方法,因为这考虑到了存在的清除按钮。
This has potentially got several complicating factors, some alluded to in previous answers:
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.
(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:
but looks right if it's just numbers
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.
在故事板中:受控 ->根据您的需要更改垂直和水平对齐方式。
In the storyboard: Under control -> change the vertical as well as horizontal alignment, as to your needs.
这对于文本字段的文本效果很好。但如果你想使用占位符文本(文本字段为空时出现的文本),在 iOS 7 上你会遇到问题。
我通过重写 TextField 类和
方法解决了这个问题。
像这样:
适用于 iOS7 及更早版本。
This works fine for textField's text. But if you want to use placeholder text (a text that will appear while textfield is blank), on iOS 7 you will encounter problems.
I solved it by overriding TextField class and
method.
Like this:
Works for both iOS7 and earlier versions.
您还可以通过调整文本基线来解决该问题。
You can also resolve the issue by adjusting the text baseline.