改變UITextField placeHolder顏色、字體 、輸入光標位置

改變UITextField placeHolder顏色、字體 、輸入光標位置等

我們有時需要定制化UITextField對象的風格,可以添加許多不同的重寫方法,來改變文本字段的顯示行為。這些方法都會返回一個CGRect結構,制定了文本字段每個部件的邊界范圍,甚至修改placeHolder顏色,字體。

– textRectForBounds://重寫來重置文字區域

– drawTextInRect://改變繪文字屬性.重寫時調用super可以按默認圖形屬性繪制,若自己完全重寫繪制函數,就不用調用super了.

– placeholderRectForBounds://重寫來重置占位符區域

– drawPlaceholderInRect://重寫改變繪制占位符屬性.重寫時調用super可以按默認圖形屬性繪制,若自己完全重寫繪制函數,就不用調用super了

– borderRectForBounds://重寫來重置邊緣區域

– editingRectForBounds://重寫來重置編輯區域

– clearButtonRectForBounds://重寫來重置clearButton位置,改變size可能導致button的圖片失真

– leftViewRectForBounds:

– rightViewRectForBounds:

通過– 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];

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容