修改UITextField的placeholder颜色共有三种方法:
/**1.使用UITextField的属性进行修改*/
//单色字体占位符的设置
NSMutableDictionary *attr = [NSMutableDictionary dictionary];
attr[NSForegroundColorAttributeName] = [UIColor grayColor];
NSAttributedString *attrStrPlaceHolder = [[NSAttributedString alloc] initWithString:@"手机号" attributes:attr];
self.phoneField.attributedPlaceholder = attrStrPlaceHolder;
//多彩字体占位符的设置
NSMutableAttributedString *attrPlaceHolder = [[NSMutableAttributedString alloc] initWithString:@"手机号"];
[attrPlaceHolder setAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]} range:NSMakeRange(0, 1)];
[attrPlaceHolder setAttributes:@{NSForegroundColorAttributeName: [UIColor yellowColor]} range:NSMakeRange(1, 1)];
[attrPlaceHolder setAttributes:@{NSForegroundColorAttributeName: [UIColor blueColor]} range:NSMakeRange(2, 1)];
self.phoneField.attributedPlaceholder = attrPlaceHolder;
/**2.创建一个继承自UITextField的类, 重写drawPlaceholderInRect:方法*/
- (void)drawPlaceholderInRect:(CGRect)rect
{
NSMutableDictionary *attr = [NSMutableDictionary dictionary];
attr[NSForegroundColorAttributeName] = [UIColor grayColor];
attr[NSFontAttributeName] = self.font;
[self.placeholder drawInRect:CGRectMake(0, 10, self.width, 25) withAttributes:attr];
}
/**3. 使用KVC来修改UITextField内部成员变量的属性, 该成员变量为_placeholderLabel*/
//创建UITextField的子类, 在其初始化方法里面添加下面的代码
[self setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];