向 UITextField 添加左侧边距
我想将 UITextField
文本的左边距设置为 10 像素。最好的方法是什么?
I want to put the left margin of a UITextField
's text at 10 px. What is the best way to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您可以通过扩展
UITextField
类并重写两个方法来实现:代码如下:
MYTextField.h
中的接口它在
MYTextField.m
中的实现>You can do it by extending
UITextField
class and overriding two methods:Here is the code:
The interface in
MYTextField.h
Its implementation in
MYTextField.m
正如我在之前的评论中所解释的,这种情况下的最佳解决方案是扩展 UITextField 类而不是使用类别,以便您可以在所需的文本字段上显式使用它。
类别旨在向现有类添加新功能,而不是覆盖现有方法。
As I have explained in a previous comment, the best solution in this case is to extend the
UITextField
class instead of using a category, so you can use it explicitly on the desired text fields.A category is intended to add new functions to an existing class, not to override an existing method.
试试这个代码
Try this code
对于 Swift 3:
创建
UITextField
的出口,例如 usernameTextField。然后在viewDidLoad()
中编写以下代码,如果需要更多空间,请将
width: 5
更改为更大的值。For Swift 3 :
Make an outlet of the
UITextField
, say usernameTextField. Then write the following code inviewDidLoad()
Change the
width: 5
to a greater value if more space is required.我希望在属性检查器中看到 IB 中的设置来调整此值。事实证明,我无意中将对齐方式和边框样式设置为与左侧填充混乱的值。
您不会认为选择左对齐和无边框有什么大不了的,但它会使单词基本上重叠或恰好到达框的边缘,并且看起来不正确。
错误:
好:
为我解决了这个问题。希望这也对其他人有帮助。
I was hoping to see a setting in IB in the property inspector to adjust this value. Turns out I had set alignment and border style inadvertently to values that messed with the padding on the left.
You wouldn't think it would be a big deal to choose left justify and no border but it makes the words basically overlap or come right to the edge of the box and it doesn't look right.
Bad:
Good:
Fixed it right up for me. Hope this helps someone else as well.
子类化 UITextField 并添加扩展:
usage
Subclass the UITextField and add an extension:
usage
我几乎通过覆盖
- (CGRect)textRectForBounds:(CGRect)bounds
来达到目的。现在的问题是,当 TextField 进入编辑模式时,它们的左边距重置为零......i have reached almost by overriding
- (CGRect)textRectForBounds:(CGRect)bounds
. now issue is when TextField goes in to edit mode their left margin reset to Zero .......对于 Swift 4:
我更喜欢使用
IBDesignable
类和IBInspectable
属性,以允许我通过 Xcode Storyboard 设置填充并保持其可重用。我还更新了代码以在 Swift 4 中工作。For Swift 4:
I prefer to use
IBDesignable
class andIBInspectable
properties to allow me to set the padding via Xcode storyboards and keep it reusable. I've also updated the code to work in Swift 4.你可以试试这个
You can try this