UITextField 看似簡單,但真要做設計稿還原,就會發現預設的 placeholder 顏色、文字與邊距都不太聽話。好消息是它提供了一整組可覆寫的方法,每一個對應畫面上的一個區域。
其中 drawTextInRect: 與 drawPlaceholderInRect: 有個共同特性:呼叫 super 會以預設樣式繪製,完全自寫則不必呼叫。若只想微調顏色,最省事的做法是設定好顏色後再呼叫 super。
@interface CustomTextField : UITextField
@end
@implementation CustomTextField
// 清除按鈕位置
- (CGRect)clearButtonRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + bounds.size.width - 50,
bounds.origin.y + bounds.size.height - 20, 16, 16);
}
// placeholder 位置:往右移 100
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + 100, bounds.origin.y,
bounds.size.width - 10, bounds.size.height);
}
// 一般文字位置:往右移 190
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + 190, bounds.origin.y,
bounds.size.width - 10, bounds.size.height);
}
// 編輯中文字位置:往右移 10
- (CGRect)editingRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + 10, bounds.origin.y,
bounds.size.width - 10, bounds.size.height);
}
// 左側附掛視圖位置
- (CGRect)leftViewRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + 10, bounds.origin.y,
bounds.size.width - 250, bounds.size.height);
}
// 改 placeholder 的顏色與字型
- (void)drawPlaceholderInRect:(CGRect)rect {
[[UIColor orangeColor] setFill];
[[self placeholder] drawInRect:rect
withFont:[UIFont systemFontOfSize:20]];
}
@end
關鍵陷阱:textRectForBounds: 與 editingRectForBounds: 必須分開覆寫。很多人只改了前者,於是「還沒點擊時位置正確,一點下去文字就跳回原位」。
_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];
如果只是要改 placeholder 顏色,其實不必覆寫 drawPlaceholderInRect:。iOS 7 之後可以直接用 attributedPlaceholder:
_textField.attributedPlaceholder =
[[NSAttributedString alloc] initWithString:@"請輸入帳號信息"
attributes:@{NSForegroundColorAttributeName: [UIColor grayColor],
NSFontAttributeName: [UIFont systemFontOfSize:14]}];
一行取代整個子類別,優先推薦。而若要調整左右內距,也可以改用 layer 的 border 搭配 contentVerticalAlignment,或乾脆自訂 UITextField 的 textRect 邊距常數,避免寫死魔法數字(例如範例中的 100、190、250)。
覆寫這組方法時機仍舊有用——特別是需要「編輯中與非編輯狀態有不同邊距」這類需求時——但先試試 attributedPlaceholder,能省下不少功夫。