咱們有時須要定製化UITextField對象的風格,能夠添加許多不一樣的重寫方法,來改變文本字段的顯示行爲。這些方法都會返回一個CGRect結構,制定了文本字段每一個部件的邊界範圍,甚至修改placeHolder顏色,字體。函數
– textRectForBounds: //重寫來重置文字區域字體
– drawTextInRect: //改變繪文字屬性.重寫時調用super能夠按默認圖形屬性繪製,若本身徹底重寫繪製函數,就不用調用super了.對象
– placeholderRectForBounds: //重寫來重置佔位符區域繼承
– drawPlaceholderInRect: //重寫改變繪製佔位符屬性.重寫時調用super能夠按默認圖形屬性繪製,若本身徹底重寫繪製函數,就不用調用super了圖片
– borderRectForBounds: //重寫來重置邊緣區域it
– editingRectForBounds: //重寫來重置編輯區域class
– clearButtonRectForBounds: //重寫來重置clearButton位置,改變size可能致使button的圖片失真方法
– leftViewRectForBounds:im
– rightViewRectForBounds:img
經過– drawPlaceholderInRect:方法可改變placeHolder顏色、字體,請看代碼:
首先定義一個類CustomTextField讓它繼承UITextField實現如下方法便可:
//控制清除按鈕的位置
-(CGRect)clearButtonRectForBounds:(CGRect)bounds
{
return CGRectMake(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);
CGRect inset = CGRectMake(bounds.origin.x+100, bounds.origin.y, bounds.size.width -10, bounds.size.height);//更好理解些
return inset;
}
//控制顯示文本的位置
-(CGRect)textRectForBounds:(CGRect)bounds
{
//return CGRectInset(bounds, 50, 0);
CGRect inset = CGRectMake(bounds.origin.x+190, bounds.origin.y, bounds.size.width -10, bounds.size.height);//更好理解些
return inset;
}
//控制編輯文本的位置
-(CGRect)editingRectForBounds:(CGRect)bounds
{
//return CGRectInset( bounds, 10 , 0 );
CGRect inset = CGRectMake(bounds.origin.x +10, bounds.origin.y, bounds.size.width -10, bounds.size.height);
return inset;
}
//控制左視圖位置
- (CGRect)leftViewRectForBounds:(CGRect)bounds
{
CGRect inset = CGRectMake(bounds.origin.x +10, bounds.origin.y, bounds.size.width-250, bounds.size.height);
return inset;
//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 = [[CustomTextField alloc] 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 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-iwant-2.png"]];
_textField.leftView = imgv;
_textField.leftViewMode = UITextFieldViewModeAlways;
[self.view addSubview:_textField];