设置UITextField的占位文字颜色三种方式
1>KVC修改 如果不先设置占位文字, 占位文字的颜色是不管用的:
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 200, 30)];
textField.placeholder = @"设置了占位文字内容以后, 才能设置占位文字的颜色";
textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
2>通过attributedPlaceholder属性修改占位文字颜色
CGFloat viewWidth = self.view.bounds.size.width;****
CGFloat textFieldX = 50;
CGFloat textFieldH = 30;
CGFloat padding = 30;
UITextField *textField = [[UITextField alloc] init];
textField.frame = CGRectMake(textFieldX, 100, viewWidth - 2 * textFieldX, textFieldH);
textField.borderStyle = UITextBorderStyleRoundedRect; // 边框类型
textField.font = [UIFont systemFontOfSize:14];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入占位文字" attributes:
@{NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName:textField.font
}];
textField.attributedPlaceholder = attrString;
[self.view addSubview:textField];
3>通过重写UITextField的drawPlaceholderInRect:方法修改占位文字颜色
步骤:
- 1.自定义一个TextField继承自UITextField
- 2.重写drawPlaceholderInRect:方法
- 3.在drawPlaceholderInRect方法中设置placeholder的属性
-(void)drawPlaceholderInRect:(CGRect)rect {
// 计算占位文字的 Size
CGSize placeholderSize = [self.placeholder sizeWithAttributes:
@{NSFontAttributeName : self.font}];
[self.placeholder drawInRect:CGRectMake(0, (rect.size.height - placeholderSize.height)/2, rect.size.width, rect.size.height) withAttributes:
@{NSForegroundColorAttributeName : [UIColor blueColor],
NSFontAttributeName : self.font}];
}