最近做的项目,UI设计的textfield中的placeholder没有顶格,并且光标的颜色,和字体的大小都比较小,全都需要自己设置.现在给记录下来,方便以后自己复用,也给有需要的同学提供点帮助.
1.首先我写了一个方法,需要两个参数,一个是当前设置的textfield,另个是placeholder的内容,代码如下:
- (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.需要的时候直接调用:
newPwdTF.attributedPlaceholder = [self changePlaceholderWithTextField:newPwdTF withString:@"请输入8-16位密码,必须同时包含数字和字母两种"];
直接改变字体大小后,placeholder位置会偏上,并不是居中显示,如图:
3.这个时候需要单独调节placeholder的位置,我的方法是重写了UITextField类,然后再重写** - (void)drawPlaceholderInRect:(CGRect)rect **方法,在此方法内部,调整placeholder的位置:
- (void)drawPlaceholderInRect:(CGRect)rect {
[super drawPlaceholderInRect:CGRectMake(0,self.bounds.size.height * 0.5 - 0.5 , 0, 0)];
}
这样之后,效果就正常了,如图: