最近做的項目,UI設計的textfield中的placeholder沒有頂格,并且光標的顏色,和字體的大小都比較小,全都需要自己設置.現(xiàn)在給記錄下來,方便以后自己復用,也給有需要的同學提供點幫助.
1.首先我寫了一個方法,需要兩個參數(shù),一個是當前設置的textfield,另個是placeholder的內(nèi)容,代碼如下:
- (NSMutableAttributedString *)changePlaceholderWithTextField:(UITextField *)textField withString:(NSString *)string{
//設置光標顏色
textField.tintColor = [UIColor colorWithRed:186/255.0 green:172/255.0 blue:110/255.0 alpha:1];
textField.textColor = [UIColor colorWithRed:186/255.0 green:172/255.0 blue:110/255.0 alpha:1];
//placeholder前面加入空格
textField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 42/2/1.5, 0)];
textField.leftViewMode = UITextFieldViewModeAlways;
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:string];
if (kScreenWidth == 320) {
[attributeString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12.0] range:NSMakeRange(0, string.length)];
}else{
[attributeString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14.0] range:NSMakeRange(0, string.length)];
}
//設置placeholder字體的顏色
[attributeString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:152/255.0 green:152/255.0 blue:152/255.0 alpha:1] range:NSMakeRange(0, string.length)];
return attributeString;
}
2.需要的時候直接調(diào)用:
newPwdTF.attributedPlaceholder = [self changePlaceholderWithTextField:newPwdTF withString:@"請輸入8-16位密碼,必須同時包含數(shù)字和字母兩種"];
直接改變字體大小后,placeholder位置會偏上,并不是居中顯示,如圖:
3.這個時候需要單獨調(diào)節(jié)placeholder的位置,我的方法是重寫了UITextField類,然后再重寫** - (void)drawPlaceholderInRect:(CGRect)rect **方法,在此方法內(nèi)部,調(diào)整placeholder的位置:
- (void)drawPlaceholderInRect:(CGRect)rect {
[super drawPlaceholderInRect:CGRectMake(0,self.bounds.size.height * 0.5 - 0.5 , 0, 0)];
}
這樣之后,效果就正常了,如圖: