如何修改UITextField中placeholder的字体和颜色。

一、通过UITextField的attributedPlaceholder属性来实现。

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 20)];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"i am placeholder."
                                                              attributes:@{NSForegroundColorAttributeName : [UIColor redColor],
                                                               NSFontAttributeName : [UIFont systemFontOfSize:6]
}];
[self.view addSubview:textField];

二、KVC

UITextField的placeholder其实就是个UILabel,我们拿到它的真实属性名,就可以通过KVC赋值了。

UITextField类结构

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 20)];
           textField.placeholder = @"i am placeholder.";
           [textField setValue:[UIFont systemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
           [textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
           // 如果你愿意的话,placehloder本身也可以通过KVC赋值
           [textField setValue:@"abc" forKeyPath:@"_placeholderLabel.text"];
           [self.view addSubview:textField];