如何在UITextField的开头添加空间

16 iphone uitextfield ios

我正在创建一个包含多个的应用程序UITextField.在textField中,我将边框类型设置为无和背景图像.它显示很好,但现在我的文字是从最小的边框开始,看起来不太好,就像这样

在此输入图像描述

如何在文本字段的开头添加空间?

Kal*_*esh 20

试试这个

UILabel * leftView = [[UILabel alloc] initWithFrame:CGRectMake(10,0,7,26)];
leftView.backgroundColor = [UIColor clearColor];

textField.leftView = leftView;

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


Apu*_*urv 9

您应该子类化UITextField并覆盖drawText函数.

检查这个以获得帮助或者你可以这样做:

UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, height_of_textfiled)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;
Run Code Online (Sandbox Code Playgroud)


ZGs*_*ski 9

这是@ Kalpesh在Swift 3.x中的答案:

let leftView = UILabel(frame: CGRectMake(10, 0.0, 7, 26))
leftView.backgroundColor = .clearColor()

customField.leftView = leftView
customField.leftViewMode = .Always
customField.contentVerticalAlignment = .Center
Run Code Online (Sandbox Code Playgroud)

Swift 4.x

let leftView = UILabel(frame: CGRect(x: 10, y: 0, width: 7, height: 26))
leftView.backgroundColor =.clear

customField.leftView = leftView
customField.leftViewMode = .always
customField.contentVerticalAlignment = .center
Run Code Online (Sandbox Code Playgroud)


Nil*_*esh 7

目标c

对于仅填充占位符,此代码将起作用

usernameTF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"    Your text"];
Run Code Online (Sandbox Code Playgroud)

为了填充UITextField的占位符和文本,下面的代码将起作用

usernameTF.layer.sublayerTransform = CATransform3DMakeTranslation(40, 0, 30);
Run Code Online (Sandbox Code Playgroud)

Swift 3.0

对于仅填充占位符,此代码将起作用

yourTextField.attributedPlaceholder = NSAttributedString(string: "    YourText")
Run Code Online (Sandbox Code Playgroud)

为了填充UITextField的占位符和文本,下面的代码将起作用

usernameTF.layer.sublayerTransform = CATransform3DMakeTranslation(40, 0, 30)
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以继承UITextField并覆盖textRectForBoundseditingRectForBounds

例如,

- (CGRect)textRectForBounds:(CGRect)bounds {
    return CGRectMake(bounds.origin.x + 10, bounds.origin.y + 5, bounds.size.width - 20, bounds.size.height - 10);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return CGRectMake(bounds.origin.x + 10, bounds.origin.y + 5, bounds.size.width - 20, bounds.size.height - 10);
}
Run Code Online (Sandbox Code Playgroud)


osc*_*lon 5

斯威夫特4

yourTextField.layer.sublayerTransform = CATransform3DMakeTranslation(10, 0, 10)
Run Code Online (Sandbox Code Playgroud)