修改TextField的占位文字的三种方法
第一种 :通过TextField的attributedPlaceholder
属性修改占位文字颜色
例如:
NSAttributedString *attr = [[NSAttributedString alloc]initWithString:@"搜索位置"attributes:@{NSForegroundColorAttributeName:[[UIColor whiteColor]}];
self.searchTextField.attributedPlaceholder = attr;
第二种 :通过继承UItextfield,然后重写-(void)drawPlaceholderInRect:(CGRect)rect
方法修改
例如:
// 修改占位文字颜色
-(void)drawPlaceholderInRect:(CGRect)rect {
// 计算占位文字的 Size
CGSize placeholderSize = [self.placeholder sizeWithAttributes:
@{NSFontAttributeName : self.font}];
CGRect drawRect = CGRectMake(0, (rect.size.height - placeholderSize.height)/2, rect.size.width, rect.size.height);
NSDictionary *attributes = @{NSForegroundColorAttributeName:[[UIColor whiteColor] colorWithAlphaComponent:0.8],NSFontAttributeName : self.font};
[self.placeholder drawInRect:drawRect withAttributes:attributes];
}
第三种 :通过KVC的方式
// 'self'指的是UITextfield
[self setValue:[[UIColor whiteColor] colorWithAlphaComponent:0.8] forKeyPath:@"_placeholderLabel.textColor"];
通过KVC的方式有一定风险,如果系统更新,官方文档中修改了一些控件的属性名称,则会导致程序崩溃