我想让占位符文本显示在文本字段的中间(填充占位符文本)。占位符文本的大小也需要增加。我的代码如下,我该如何解决?
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(30, 220,250,55)];
textField.placeholder=@"iiiiiii";
UIView *padView = [[UIView alloc] initWithFrame:CGRectMake(10, 110, 10, 0)];
textField.leftView = padView;
textField.leftViewMode = UITextFieldViewModeAlways;
[self.view addSubview:textField];
更新
我希望占位符文本的字体大小增加your name
,并且它应该有一个左边填充。
答案 0 :(得分:13)
您可以继承UITextFiled
并覆盖方法:
MyTextField.m
- (CGRect)textRectForBounds:(CGRect)bounds {
return [self rectForBounds:bounds];
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self rectForBounds:bounds];
}
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
return [self rectForBounds:bounds];
}
//here 40 - is your x offset
- (CGRect)rectForBounds:(CGRect)bounds {
return CGRectInset(bounds, 40, 3);
}
<强> UPD:强> 还设置了
textFiled.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
因为io6与ios 7垂直定位可能存在一些问题
答案 1 :(得分:3)
同样的问题被问及并回答如下Set padding for UITextField with UITextBorderStyleNone
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;
答案 2 :(得分:2)
您可以将起始文本对齐方式(xib中的{{1>}或通过代码的)设置为居中对齐。
然后在textField
中,您可以将-textFieldShouldBeginEditing
设置为左对齐
同样,在textField
上,检查-textFieldDidEndEditing
是否为空,如果是,则将textField
设置为居中对齐。
基本上是:
textField
编辑::
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
[textField setTextAlignment:NSTextAlignmentLeft];
return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
if(textField.text.length == 0) {
[textField setTextAlignment:NSTextAlignmentCenter];
}
}
课程的 .h 应如下所示:
ViewController
现在,用这个替换你的其他代码:
@interface ViewController : UIViewController <UITextFieldDelegate>
{
UITextField *myTextField;
}
答案 3 :(得分:1)
sampleTextfield.leftView = UIView(frame: CGRectMake(0, 0, 20, self.sampleTextfield.frame.height))
sampleTextfield.leftViewMode = UITextFieldViewMode.Always
答案 4 :(得分:0)
我发现在swift 2和Xcode 7上执行此任务的最简单方法:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let paddingView = UIView(frame: CGRectMake(0, 0, 25, self.emailTextField.frame.height))
emailTextField.leftView = paddingView
emailTextField.leftViewMode = UITextFieldViewMode.Always
}
}
答案 5 :(得分:0)
func placeholderPadding(textField:UITextField, leftPadding:CGFloat) {
textField.leftView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: leftPadding, height: textField.frame.height))
textField.leftViewMode = UITextFieldViewMode.always
}
答案 6 :(得分:-2)
虽然我没有专门测试过,但这应该有效:
self.YourTextField.attributedPlaceholder = NSAttributedString(string: " YourText")
将空格(填充)的数量添加到字符串
答案 7 :(得分:-3)
只需按几下空格键即可从左侧填充占位符文字。
text
与
text