如何在UITextField的开头添加空格

我正在创build一个包含多个UITextField的应用程序。 在textField中,我将边框types设置为none和背景图像。 它显示得很好,但现在我的文本是从最好的边框开始,这样看起来不太好

在这里输入图像说明

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

尝试这个

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

您应该inheritanceUITextField并覆盖drawText函数。

检查此帮助或您可以执行以下操作:

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

这里是@ 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 

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 

您可以inheritanceUITextField和ovverride textRectForBounds和editingRectForBounds。 例如,

 - (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); } 

目标c

对于填充只有占位符这个代码将工作

 usernameTF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@" Your text"]; 

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

 usernameTF.layer.sublayerTransform = CATransform3DMakeTranslation(40, 0, 30); 

Swift 3.0

对于填充只有占位符这个代码将工作

 yourTextField.attributedPlaceholder = NSAttributedString(string: " YourText") 

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

 usernameTF.layer.sublayerTransform = CATransform3DMakeTranslation(40, 0, 30) 
 -(void)textField:(UITextField *) textField didBeginEditing { if ([textField.text isEqualToString:@""] || textField.text == NULL) { textField.text = @" "; } } 

您可以将文本框背景图像放在图像视图中,在图像视图上方放置您的文本框。