通过– drawPlaceholderInRect:方法可改变placeHolder颜色、字体,请看代码:
首先定义一个类CustomTextField让它继承UITextField实现以下方法即可:
//控制清除按钮的位置
-(CGRect)clearButtonRectForBounds:(CGRect)bounds
{
returnCGRectMake(bounds.origin.x+ bounds.size.width-50, bounds.origin.y+ bounds.size.height-20,16,16);
}
//控制placeHolder的位置,左右缩20
-(CGRect)placeholderRectForBounds:(CGRect)bounds
{
//return CGRectInset(bounds, 20, 0);
CGRectinset =CGRectMake(bounds.origin.x+100, bounds.origin.y, bounds.size.width-10, bounds.size.height);//更好理解些
returninset;
}
//控制显示文本的位置
-(CGRect)textRectForBounds:(CGRect)bounds
{
//return CGRectInset(bounds, 50, 0);
CGRectinset =CGRectMake(bounds.origin.x+190, bounds.origin.y, bounds.size.width-10, bounds.size.height);//更好理解些
returninset;
}
//控制编辑文本的位置
-(CGRect)editingRectForBounds:(CGRect)bounds
{
//return CGRectInset( bounds, 10 , 0 );
CGRectinset =CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width-10, bounds.size.height);
returninset;
}
//控制左视图位置
- (CGRect)leftViewRectForBounds:(CGRect)bounds
{
CGRectinset =CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width-250, bounds.size.height);
returninset;
//return CGRectInset(bounds,50,0);
}
//控制placeHolder的颜色、字体
- (void)drawPlaceholderInRect:(CGRect)rect
{
//CGContextRef context = UIGraphicsGetCurrentContext();
//CGContextSetFillColorWithColor(context, [UIColor yellowColor].CGColor);
[[UIColororangeColor]setFill];
[[selfplaceholder]drawInRect:rectwithFont:[UIFontsystemFontOfSize:20]];
}
//下面是使用CustomTextField的代码,可放在viewDidLoad等方法中
_textField= [[CustomTextFieldalloc]initWithFrame:CGRectMake(20,150,280,30)];
_textField.placeholder=@"请输入帐号信息";
_textField.borderStyle=UITextBorderStyleRoundedRect;
_textField.textAlignment=UITextAlignmentLeft;
_textField.delegate=self;
_textField.clearButtonMode=UITextFieldViewModeWhileEditing;
_textField.text=@"aa";
UIImageView*imgv = [[UIImageViewalloc]initWithImage:[UIImageimageNamed:@"icon-iwant-2.png"]];
_textField.leftView= imgv;
_textField.leftViewMode=UITextFieldViewModeAlways;
[self.viewaddSubview:_textField];