16

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

在此处输入图像描述

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

4

8 回答 8

20

尝试这个

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

textField.leftView = leftView;

textField.leftViewMode = UITextFieldViewModeAlways;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
于 2013-06-17T11:01:39.860 回答
9

您应该UITextField继承并覆盖 drawText 函数。

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

UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, height_of_textfiled)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;
于 2013-06-17T11:01:17.643 回答
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

斯威夫特 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
于 2016-04-27T17:37:45.197 回答
7

目标c

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

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

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

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

斯威夫特 3.0

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

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

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

usernameTF.layer.sublayerTransform = CATransform3DMakeTranslation(40, 0, 30)
于 2017-05-18T11:45:31.363 回答
5

您可以继承UITextField和覆盖textRectForBoundsand 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);
}
于 2013-06-17T11:22:57.293 回答
5

斯威夫特 4

yourTextField.layer.sublayerTransform = CATransform3DMakeTranslation(10, 0, 10)
于 2018-10-22T19:21:37.983 回答
1

您可以将文本字段背景图像放在图像视图中,在图像视图上方将文本字段留出空间。

于 2013-06-17T11:28:16.000 回答
-1
-(void)textField:(UITextField *) textField didBeginEditing {
    if ([textField.text isEqualToString:@""] || textField.text == NULL) {
       textField.text = @" ";
    }
}
于 2013-06-17T11:27:13.623 回答